gpt4 book ai didi

java - 编辑程序以使用 Java 中用户输入的 do while/while 循环

转载 作者:行者123 更新时间:2023-11-29 04:20:44 28 4
gpt4 key购买 nike

我是 Java 的新手,所以我对语法没有太多经验,我尝试了一些在线教程并观看了一些关于用户输入的 Java 中 while 和 do while 循环的视频。但是,我尝试的每一次编辑都会破坏我的代码。下面的程序从用户那里获取一个答案,一个从 1 到 20 的整数,并有执行不同场景的 if 语句。但是,我正在努力做到这一点,以便它会不断询问用户的答案,直到他们输入 0。这是相关代码的一部分:

System.out.print("Type in the pokedex number of the pokemon:");
int answer = Integer.parseInt(reader.nextLine());
if (answer == 1){
System.out.println(
"\nPokemon: " + Bulbasaur.getname() +
"\nType: " + Bulbasaur.getthing_about() +
"\nHealth: " + Bulbasaur.gethp() +
"\nAttack: " + Bulbasaur.getattack() +
"\nDefense: " + Bulbasaur.getdefense() +
"\nSpecial attack: " + Bulbasaur.getspattack() +
"\nSpecial defense: " + Bulbasaur.getspdefense()+
"\nSpeed: " + Bulbasaur.getspeed() +
"\nTotal: " + Bulbasaur.gettotal());
}

...

还有 19 个其他类似的 if 语句(我知道这是低效的代码,但如果它循环,我会让它变得高效)。我将如何添加一个 do while/while 循环来循环这些语句直到输入 0?

最佳答案

您需要检查循环条件中的answer。您可以在一行中进行检查和分配以回答

int answer;
while ((answer = Integer.parseInt(reader.nextLine())) != 0) {
// code here
}

关于java - 编辑程序以使用 Java 中用户输入的 do while/while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49347430/

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