i.n.n.m i.n.n.m - 3 years ago 131
Java Question

Repeat a set of instruction with while loop - Java

I am getting user inputs do some calculation and then repeatedly ask the user to take repeatedly until a Sentinel value (3 in my case) entered.

I am using

do-while
loop and it does not give my desired output as shown below,

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);
}
}


I am getting the following output,

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


However, I need something like this,(prompts the user to select the number not
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:


What am I doing wrong in my
do
statement? Any thought would be appreciated!

Answer Source

It looks to me like you need to move do { up a few lines.

Only the part between do { and while gets repeated, and you need that to include asking the user for which type of problem they want, and generating the random numbers.

However, you will need to declare userInput before do if you want to use it as the while condition.

    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 ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download