iluusion
iluusion

Reputation: 19

Input validation using a separate method

How do I check the user answer of a simple equation using a different method. This is what I currently have:

public static void generateSubtraction() {

    Random rand2 = new Random();
    Scanner keyboard4 = new Scanner(System.in);

    int max = 100;
    int min = 1;

    int random = rand2.nextInt(50);
    int random2 = rand2.nextInt(50);

    int n = random - random2;
    System.out.println(random + " - " + random2 + " = ?");
    int x = keyboard4.nextInt();

    if (n == x) {

        System.out.println("Correct!");
    }
    if (n != x) {

        System.out.println("Wrong!");
    }

This is the part that I want in a completely separate method:

    if (n == x) {

        System.out.println("Correct!");
    }
    if (n != x) {

        System.out.println("Wrong!");
    }

Not sure how to use the answer input in the first method and check it in the second method. I'm required to call both methods from the main method.

Upvotes: 0

Views: 271

Answers (2)

0xDEADBEEF
0xDEADBEEF

Reputation: 590

if you want to call both methods you can create an array for int n and x then provide a return type to be an array

    public static int[] generateSubtraction() {

        Random rand2 = new Random();
        Scanner keyboard4 = new Scanner(System.in);

        int max = 100;
        int min = 1;

        int random = rand2.nextInt(50);
        int random2 = rand2.nextInt(50);

        int n = random - random2;
        System.out.println(random + " - " + random2 + " = ?");
        int x = keyboard4.nextInt();
        int[] numbers={n,x};
        return numbers;
}

then

public static void getArray(int[] numbers)

    {
        if(numbers[0]==numbers[1])
         //code code code
        else
            //code code code

    }

then at main

getArray(generateSubstraction());

Upvotes: 0

user6004556
user6004556

Reputation:

Why not just make another void method?

public void printAnswer(int n, int x){
    if (n == x) {

        System.out.println("Correct!");
    }
    if (n != x) {

        System.out.println("Wrong!");
    }
}

call it by using: printAnswer(n, x);

Upvotes: 1

Related Questions