我正在尝试制作简单的java应用程序,它在屏幕上输出两个数字,用户必须输入这两个数字的总和。当我输入总和时,如果是正确的程序问我是否要继续。如果我说是,则程序输出两个新数字,当我输入正确答案时,程序不能识别答案是否正确。
如果我在程序开始时输错了答案,我希望程序一遍又一遍地询问用户解决方案,直到他输入正确的答案,但我不知道该怎么做。这是我的代码:
import java.util.Scanner;
import java.security.SecureRandom;
public class HelloWorld {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int result = getRandomNumbers();
int counter = 1;
char again;
while (counter == 1) {
int userResult = input.nextInt();
if (result == userResult) {
System.out.println("You are right");
} else {
System.out.println("You are wrong, try again");
}
System.out.println("Do you want to try again? Enter y for yes or n for no");
again = input.next().charAt(0);
if (again == 'y') getRandomNumbers();
else counter++;
}
}
public static int getRandomNumbers() {
SecureRandom randomNumbers = new SecureRandom();
int fnum = 1 + randomNumbers.nextInt(9);
int snum = 1 + randomNumbers.nextInt(9);
System.out.println("What is " + fnum + " times " + snum);
return fnum * snum;
}
}
答案 0 :(得分:1)
如果输入不是预期输入,您可以使用while
循环询问用户输入新内容。
试试这个:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
int result = getRandomNumbers();
int userResult = input.nextInt();
while ( result != userResult) {
System.out.println("You are wrong, try again");
result = getRandomNumbers();
userResult = input.nextInt();
}
System.out.println("You are right");
System.out.println("Do you want to try again? Enter y for yes or n for no");
if (input.next().charAt(0) == 'n') {
break;
}
}
只有在用户说他不想继续(while (true)
)时才会中断n
循环。