Pergunta

I've hit a brick wall with a Java project that I've been working on casually over the past several weeks. The majority of the code works properly, however, the loops in my program are creating an incorrect sequence of events.

Basically what I'd like the program to do is ask a math question, have the user guess the answer, and if he/she is correct, print the menu out again. If the user is incorrect, it should ask them to keep guessing until correct. However, this isn't what's happening. The responses are correct, however, when the user gets a correct answer it takes the randomly generated numbers in the array and continues through the switch statement, essentially asking the user the same numbers but with a different math question (addition --> multiplication --> etc.).

If anyone could provide me with some pointers as to what I've done incorrectly, and where to look so that I can remedy this problem, I would greatly appreciate it.

Thank you.

import java.util.Scanner;
import java.util.Random;

public class MathTutor {

    public static int[] randomNumbers(){
        Random obj = new Random();

        int arr[] = new int[2];   //init array to hold 2 numbers

        arr[0] = obj.nextInt(99); //number 1 randomized 0 - 9 // sort array
        arr[1] = obj.nextInt(99); //number 2 randomized 0 - 9
        if (arr[1] > arr[0]) {
            int temp = arr[0];
            arr[0] = arr[1];
            arr[1] = temp;
        }

        //do compare to make sure arr[0] is always greater than arr[1]
        //but how???

        return arr;

        /*int rgen = obj.nextInt(10); //first number has to be larger than second 0 - 10
        int rgen1 = obj.nextInt(9); //random 0 - 9
        int randomNumber = rgen + rgen1; //stores the answer*/
    }

    public static void menu(){
        System.out.println("1. Addition Problem");
        System.out.println("2. Subtraction Problem");
        System.out.println("3. Multiplication Problem");
        System.out.println("4. Division Problem");
        System.out.println("5. Exit Program");
        System.out.print("Welcome! Please make a selection: ");
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int number[]; //new int[2];
        int answer;
        int choice;

        do {

            menu(); // calls the menu method

            choice = input.nextInt(); // select from menu()

            number = randomNumbers(); //populates random numbers into arrays

            if (choice <= 0 || choice >= 6)
            {
                System.out.println("Incorrect choice!");
                System.out.println("1. Addition Problem");
                System.out.println("2. Subtraction Problem");
                System.out.println("3. Multiplication Problem");
                System.out.println("4. Division Problem");
                System.out.println("5. Exit Program");
                System.out.print("Welcome! Please make a selection: ");

                choice = input.nextInt();
            }

            switch (choice)
            {
                case 1:
                {
                    //Addition
                    System.out.print("What's " +number[0]+ " plus " +number[1]+ "?\n");
                    answer = input.nextInt();
                    if(answer == (number[0]+number[1])){
                        System.out.println("\nCorrect!");
                    }
                    else{
                        System.out.println("No! Please try again.");
                    }

                    menu();
                }
                case 2:
                {
                    //Subtraction
                    System.out.print("What's " +number[0]+ " minus " +number[1]+ "?\n");
                    answer = input.nextInt();
                    if(answer == (number[0]-number[1])){
                        System.out.println("\nCorrect!");
                    }
                    else{
                        System.out.println("No! Please try again.");
                    }

                    menu();
                }
                case 3:
                {
                    //Multiplication
                    System.out.print("What's " +number[0]+ " multiplied by " +number[1]+ "?\n");
                    answer = input.nextInt();
                    if(answer == (number[0]*number[1])){
                        System.out.println("\nCorrect!");
                    }
                    else{
                        System.out.println("No! Please try again.");
                    }

                    menu();
                }
                case 4:
                {
                    //Division
                    System.out.print("What's " +number[0]+ " divided " +number[1]+ "?\n");
                    answer = input.nextInt();
                    if(answer == (number[0]/number[1])){
                        System.out.println("\nCorrect!");
                        System.out.println(number[0]+ " divided by " +number[1]+ " is "
                                +answer+ " remainder " +(number[0] % number[1]));
                    }
                    else{
                        System.out.println("No! Please try again.");
                    }

                    menu();
                }
                case 5:
                {
                    //Exit
                    System.out.print("\nHave a nice day!");
                    System.exit(0);
                }
                default:

            }

            //Below, the code works fine. Use it as a template.
        /*do {
            number = randomQuestion();
            do {
                System.out.print("\nHow much is " + number[0] + " times " + number[1]+ " ? :");
                answer = input.nextInt();
                if(answer == (number[0]*number[1])){
                    System.out.print("\nCorrect!");
                }
                else{
                    System.out.print("No! Please try again.");
                }
        }*/
        }
        while(choice < 0 || choice > 6);
        {
            System.out.println("1. Addition Problem");
            System.out.println("2. Subtraction Problem");
            System.out.println("3. Multiplication Problem");
            System.out.println("4. Division Problem");
            System.out.println("5. Exit Program");
            System.out.print("Welcome! Please make a selection: ");

            //choice = input.nextInt();
        }
    }
}
Foi útil?

Solução 2

When retrieving an int with Scanner, remember to do a nextLine() to advance to the next line. Your case statements will run into each other because you do not have a break statement. And generally speaking, think about how the loop executes your statements and simplify things. For example (I only implemented add):

import java.util.Scanner;
import java.util.Random;

public class MathTutor {
    private static Random obj = new Random();

    public static int[] randomNumbers(){
        int arr[] = new int[2];   //init array to hold 2 numbers

        int x = obj.nextInt(99);
        int y = obj.nextInt(99);

        arr[0] = Math.max(x,y);
        arr[1] = Math.min(x, y);

        return arr;
    }

    public static void menu(){
        System.out.println("1. Addition Problem");
        System.out.println("2. Subtraction Problem");
        System.out.println("3. Multiplication Problem");
        System.out.println("4. Division Problem");
        System.out.println("5. Exit Program");
        System.out.print("Welcome! Please make a selection: ");
    }

    public static void main(String[] args) {

        int choice, answer;
        int[] number;
        Scanner input = new Scanner(System.in);

        do {
            menu();

            //get user's choice
            choice = input.nextInt();
            input.nextLine(); //ignore the rest of the line

            switch (choice)
            {
            case 1:
                number = randomNumbers();
                do {
                    System.out.print("What's " +number[0]+ " plus " +number[1]+ "?\n");
                    answer = input.nextInt();
                    input.nextLine();
                    if (answer != (number[0]+number[1]))
                        System.out.println("No! Please try again.");
                } while (answer != (number[0]+number[1]));

                System.out.println("\nCorrect!");           
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                break;
            case 5:
                break;
            default:
                System.err.println("*** invalid selection ***");
                break;
            }
        } while (choice != 5);
        input.close();
        System.out.println("bye.");
    }
}

Outras dicas

Case statements in a switch will continue on unless you put a break/return/etc. statement to tell the program to go elsewhere.

For example:

switch(number) {
    case 0: {
        // do stuff
    }
    case 1: {
        // If number was 0 this case would still be entered!
        // The program "fell through" the end of case 0 and got here
    }
    ...
}

This is called switch fallthrough. Seems like an annoyance at times, but it does have its uses:

switch(number) {
    case 0:
    case 1:
    case 2: {
        // Do something if number is 0, 1, or 2
    }
    ...
}

To avoid fallthrough, add a break statement at the end of the case. This will cause the program to jump to the end of the switch statement:

switch(number) {
    case 0: {
        // do stuff
        break; // <-- Now if number is 0 case 1 won't be entered!
    }
    case 1: {
        // Only entered if number == 1 now
    }
    ...
}

You can also put return statements to exit a method entirely from a switch statement.

Also, minor quibble: Please use a more descriptive name than obj for your Random object. Also, the general convention for declaring arrays is to put the square brackets with the type, not with the name:

int[] arr; // conventional way of declaring arrays in Java
int arr[]; // works, but doesn't follow convention. Usually not a big deal, but still...

Also, when validating that the user's input was one of the options, you should use a do-while loop. The way you have it now, if I input an invalid value twice your code would still move on. And you have the menu() method; why not use that instead of all the System.out.println() calls?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top