gpt4 book ai didi

java - 如何将 IndexOf 与 Scanner 结合使用?

转载 作者:行者123 更新时间:2023-12-02 13:13:12 25 4
gpt4 key购买 nike

我是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())));

最佳答案

But the result is always -1. And I don't understand why.

返回-1的唯一情况是没有出现指定的String

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

例如

y = sc.nextLine();

关于java - 如何将 IndexOf 与 Scanner 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43859840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com