用while循环重复一组指令 - Java

时间:2017-09-30 02:29:46

标签: java loops do-while

我正在获取用户输入进行一些计算,然后反复要求用户重复进行,直到输入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声明中做错了什么?任何想法都将不胜感激!

2 个答案:

答案 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更实用