gpt4 book ai didi

java - 如何用用户输入的字符串结束 do while 循环?

转载 作者:行者123 更新时间:2023-12-01 18:17:02 24 4
gpt4 key购买 nike

public static void main (String[] args)
{
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
String sentence = keyboard.nextLine();

System.out.print("Enter a letter: ");
String fullLetter = keyboard.nextLine();
char letter = fullLetter.charAt(0);
keyboard.nextLine();

int amount = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
amount++;
}
}

System.out.println(letter + " appears " + amount + " times in " + sentence);

System.out.print("Continue? ");
String decide = keyboard.nextLine();
} while (decide.equals("yes"));
}

}

我希望用户在循环结束时输入"is"或“否”,然后我希望该输入确定程序是否会再次循环。就目前而言,我的代码的最后一行不起作用。我环顾四周,不确定应该做什么来解决这个问题。

最佳答案

您需要在循环外部声明变量decide并在内部初始化:

String decide;
do {
//do something ...
decide = keyboard.nextLine();
} while (decide.equals("yes"));

关于java - 如何用用户输入的字符串结束 do while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28945098/

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