我正在编写一个程序,它从用户那里获取一个字符串,并用分隔符逐字分隔它,它几乎完成了。但是,在第一个完整循环之后,用户的下一个输入不会通过最后一个 while 循环。
这是我正在讨论的代码段:
do
{
System.out.println ("\nEntered String: " + s1 + "\n");
while (input.hasNext())
{
word++;
System.out.println ("Word #" + word + ": \t" + input.next());
}
System.out.print ("\nEnter 'q' to quit, enter string to continue: \t");
s1 = scan.nextLine();
} while (!s1.equals("q"));
我认为我需要另一个 while 循环来围绕单词增量和打印行,并在 input.hasNext() 循环中包含 continue 序列,因为这就是我使用 int 获得类似程序的方式,但我不确定它如何与字符串一起使用。
有什么建议吗?
编辑:澄清一下,现在我的代码的输出如下所示:
输入一个句子:这是一个句子
输入的字符串:这是一个句子
单词#1:这个
单词#2:是
单词#3:a
单词#4:句子
输入“q”退出,输入字符串继续:另一句话
输入的字符串:另一句话
输入“q”退出,输入字符串继续:
我需要“另一个句子”来打印,例如“这是一个句子”
最佳答案
我不明白到底是什么问题,因为您的代码无法编译。但不需要另一个循环。这是一些有效的代码:
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter a sentence:");
String s1 = scan.nextLine();
do
{
System.out.println("\nEntered String: " + s1 + "\n");
Scanner input = new Scanner(s1);
int word = 0;
while (input.hasNext())
{
word++;
System.out.println("Word #" + word + ": \t" + input.next());
}
System.out.print("\nEnter 'q' to quit, enter string to continue: \t");
s1 = scan.nextLine();
} while(!s1.equals("q"));
scan.close();
关于java - 如何将字符串输入保持在循环内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32982063/