【发布时间】:2023-04-01 20:35:01
【问题描述】:
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();
}
【问题讨论】:
标签: string input while-loop java.util.scanner