我试图找出用户输入的短语中是否至少有 2 个单词。如果没有,请继续要求他们输入一个短语,直到他们输入至少包含 2 个单词的短语。
到目前为止,这是我的代码:它可以成功检测他们是否输入了 2 个单词,并且成功检测到他们第一次没有输入 2 个单词,但如果他们第二次再次输入低于 2 个单词,则程序退出。
private static void stringfunctions() {
String phrase;
int count = 0;
Scanner input = new Scanner(System.in);
while (count < 2) {
System.out.println("Please enter a multiple word phrase: ");
phrase = input.nextLine();
String[] arrPhrase = phrase.split(" ");
for (int i = 0; i < arrPhrase.length; i++) {
if (arrPhrase[i].equals(" ")) {
} else {
count++;
}
}
}
最佳答案
测试后重置计数。问题是一旦 count 通过 2,while 循环就会终止
关于java - 尝试查找字符串中是否至少有 2 个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7881104/