如何将IndexOf与Scanner一起使用?

时间:2017-05-09 02:00:04

标签: java java.util.scanner indexof

我是Java的初学者,所以我很抱歉,如果这对你来说太容易回复了,我仍然希望我能从这里得到一些帮助。

我想通过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())));

1 个答案:

答案 0 :(得分:1)

  

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

唯一可以返回-1的情况是,如果没有指定的String出现这种情况。

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

e.g。

y = sc.nextLine();