gpt4 book ai didi

string - 在 while 循环中使用 hasNextInput() 它为给定的每个字符串提供循环,但我希望它提示一次

转载 作者:行者123 更新时间:2023-12-02 01:16:14 25 4
gpt4 key购买 nike

    public void choice(){

this.damageCalculator();
story.typeWriterEffect("Give your choice of attack: \n");

while (!input.hasNextInt()){
story.typeWriterEffect("Please enter the correct number (1, 2 or 3).(ERROR NO INT)\n");
story.typeWriterEffect("Give your choice of attack: \n");
input.reset();
input.next();
}
setUserChoiceOfAttack(input.nextInt());

if(getUserChoiceOfAttack() > 0 && getUserChoiceOfAttack() < 4){
this.userAttackMoment();
} else {
story.typeWriterEffect("Please enter the correct number (1, 2 of 3).(ERROR INPUT INVALID)\n");
this.choice();
}
}

问题:如果您在输入中输入“Lol nope”,那么它将输出“请输入...”和“给出您的选择...”两次(对于输入的每个单词并用空格分隔。一切运行良好,但困扰我的一件事是,如果用户输入他不应该输入的内容(即使它是由空格分隔的多个字符串),我只希望它重复一次。

这里是新手程序员,非常感谢对我的代码编写的任何反馈!

编辑:

pivu0 的评论成功了!这是我的固定代码,可以完美运行!

public void choice(){

this.damageCalculator();

story.typeWriterEffect("Give your choice of attack: \n");

boolean loopCondition = true;
while(loopCondition == true){

try{
player.setPlayerChoiceOfAttack(Integer.parseInt(input.nextLine()));

if(player.getPlayerChoiceOfAttack() > 0 && player.getPlayerChoiceOfAttack() < 4){
loopCondition = false;
} else {
story.typeWriterEffect("Please enter the correct number (1, 2 of 3).(ERROR INPUT INVALID)\n");
}
}
catch (NumberFormatException e){
loopCondition = true;
story.typeWriterEffect("Please enter the correct number (1, 2 or 3).(ERROR NO INT)\n");
story.typeWriterEffect("Give your choice of attack: \n");
}
}
this.userAttackMoment();
}

最佳答案

根据您使用的方法,我假设输入是 Scanner 的一个实例。

如果您阅读了hasNextInt 的文档https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()

您会看到它检查下一个 TOKEN 是否为 int。对于扫描器类,标记由空格分隔。所以它会检查你的第一个词,得出 'lol' 不是 Int 的结论,进行循环,得出 'nop' 不是 Int 的结论,再次进行循环...

尝试将整个扫描仪输入作为字符串 input.nextLine() 并尝试使用 Integer.parseInt 检查此字符串是否为整数

如果 input.nextLine() 是一个整数,它就会跳出循环。如果不是,则检查新输入:

int number=0;
boolean loopCondition = false;
while(!loopCondition){
try {
number = Integer.parseInt(input.nextLine())
loopCondition = true;
}
catch (NumberFormatException e){
story.typeWriterEffect("Please enter the correct number (1, 2 or 3).(ERROR NO INT)\n");
story.typeWriterEffect("Give your choice of attack: \n");
loopCondition = false;
}
}

关于string - 在 while 循环中使用 hasNextInput() 它为给定的每个字符串提供循环,但我希望它提示一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42475359/

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