我想要做的就是这样做,以便当通过一些猜测时,它会使它显示相同的消息,直到它们关闭并重新进入应用程序但我无法弄清楚如何这样做。
我目前的游戏代码是:
String randtext ="";
Random rand = new Random();
int noofguess = 0;
int n = rand.nextInt(20)+1; //generate random number
int userguess = Integer.parseInt(etCommentInput.getText().toString());
if (userguess < 1 || userguess > 20){
tvCommentOuput.setText("Please enter a number between 1-20!");
}
else if (userguess == n){
tvCommentOuput.setText("You Got It Right!");
} else if (userguess > n) {
tvCommentOuput.setText("Number too high!");
noofguess = noofguess + 1;
} else{
tvCommentOuput.setText("Number too low!");
noofguess = noofguess + 1;
}
tvCommentOuput.setText("Please enter a number between 1-20!");
randtext = Integer.toString(n);
}
}
我想要做的是在if语句中围绕它,这样如果noofguess小于3,它将运行常规程序,但如果它高于3,那么它只会显示它们已经用尽猜测但是似乎不起作用。
答案 0 :(得分:0)
解决方案是使用while循环包围部分代码
String randtext ="";
Random rand = new Random();
int noofguess = 0;
int n = rand.nextInt(20)+1; //generate random number
do{
int userguess = Integer.parseInt(etCommentInput.getText().toString());
if (userguess < 1 || userguess > 20){
tvCommentOuput.setText("Please enter a number between 1-20!");
}
else if (userguess == n){
tvCommentOuput.setText("You Got It Right!");
break;
} else if (userguess > n) {
tvCommentOuput.setText("Number too high!");
noofguess = noofguess + 1;
} else{
tvCommentOuput.setText("Number too low!");
noofguess = noofguess + 1;
}
tvCommentOuput.setText("Please enter a number between 1-20!");
randtext = Integer.toString(n);
}
while(noofguess < 3);
// add if statement here to deal with the case where there are too many guesses