您好,我有一个关于 .nextLine 的使用以及为什么它在无限循环期间第二次跳过用户输入的问题。 .next 函数(字母输入)仍然每次都要求用户输入,但 .nextLine 函数(短语输入)不会。谢谢。
import java.util.Scanner;
public class Lab6 {
public static void main (String [] args) {
Scanner in = new Scanner(System.in);
String phrase, l;
char letter;
while (true) {
System.out.println("Enter a phrase. Enter 'quit' to quit.");
phrase = in.nextLine();
if (phrase.startsWith("quit")) {
break;
}
System.out.println("Enter a letter");
l = in.next();
letter = l.charAt(0);
System.out.println("Phrase entered is: " + phrase);
System.out.println("Letter entered is: " + letter);
int i = 0;
int count = 0;
while (i < phrase.length()) {
if (phrase.charAt(i) == letter) {
count++;
}
i++;
}
System.out.println(count);
}
}
}
最佳答案
原因是 Scanner.next()
不消耗系统输入的换行符,所以输入将传递给语句:
phrase = in.nextLine();
现在不会阻止接收到输入。
关于java - 无限循环,.nextLine() 用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13220542/