我正在获取用户输入进行一些计算,然后反复要求用户重复进行,直到输入Sentinel值(在我的情况下为3)。
我正在使用do-while
循环,它没有提供我想要的输出,如下所示,
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("1: Addition");
System.out.println("2: Multiplication");
System.out.println("3: Exit");
System.out.print("Please choose a number: ");
int userinput = input.nextInt();
// Generate two random numbers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
do {
if (userinput == 1) {
System.out.print("What is " + number1 + " + " + number2);
int answer = input.nextInt();
int tureanswer = number1 + number2;
if (answer == tureanswer){
System.out.println("You're correct");
}
else
System.out.println("Wrong,correct answer is " + tureanswer);
}
if (userinput == 2) {
System.out.print("What is " + number1 + " * " + number2 + " : ");
int answer = input.nextInt();
int tureanswer = number1 * number2;
if (answer == tureanswer){
System.out.println("Correct");
}
else
System.out.println("Wrong. The correct answer is "+ tureanswer);
}
}while(userinput !=3);
}
}
我收到以下输出,
1: Multiplication
2: Addition
3: Exit
Please choose a number: 1
What is 9 + 1 12
Wrong,correct answer is 10
What is 9 + 1
但是,我需要这样的东西,(提示用户选择不是what is 9 + 1
的数字)
1: Addition
2: Multiplication
3: Exit
Please choose a number: 1
What is 9 + 1 12
Wrong,correct answer is 10
1: Addition
2: Multiplication
3: Exit
Please choose a number:
我在do
声明中做错了什么?任何想法都将不胜感激!
答案 0 :(得分:2)
在我看来,您需要将do {
向上移动几行。
只有do {
和while
之间的部分会被重复,您需要包括询问用户他们想要的问题类型,并生成随机数。
但是,如果您想将其用作userInput
条件,则需要在 do
之前声明while
。
int userInput;
do {
System.out.print("Please choose a number: ");
userinput = input.nextInt();
// Generate two random numbers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
if (userinput == 1) {
// and so on ...
答案 1 :(得分:0)
在
中添加以下行System.out.println("1: Multiplication");
System.out.println("2: Addition");
System.out.println("3: Exit");
System.out.print("Please choose a number: ");
int userinput = input.nextInt();
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
我还建议您使用switch in do while,因为它比if else更实用