2017-05-09 79 views
0

我是一名Java初学者,所以我很抱歉如果你看起来太容易回复,我希望我能从这里得到一些帮助。如何在扫描仪上使用IndexOf?

我想从用户输入Scanner,输入一个句子。 然后用户会从该句中选择一个单词。 然后与string.indexof(""),该程序应该从该句子中该词开始于哪个数字开始计数。 但结果总是-1。我不明白为什么。

String a,b; 

Scanner sc= new Scanner(System.in); 
System.out.println("Please write a sentence"); 
y=sc.next(); 

Scanner sc2 = new Scanner(System.in); 
System.out.println("Please pick a word from that sentence"); 

System.out.println("The word starts from=" + (y.indexOf(a=sc2.next()))); 
+0

尝试打印“y”和值“A = sc2.next()”中的控制台的用户键入他们之后,然后给我们输出 –

回答

1

但结果始终是-1。我不明白为什么。

将返回-1唯一的情况是,如果没有指定的String这种情况发生。

Scanner#next()只返回空格之前的内容,表示空格之后的任何内容被忽略。看起来您需要使用Scanner#nextLine来存储整个句子,而不是Scanner#next()

例如

y = sc.nextLine(); 
+1

太感谢你了,它的工作:) –