Home > Software engineering >  Check if user input matches answer to sum of 2 random Numbers
Check if user input matches answer to sum of 2 random Numbers

Time:06-11


Hi Im trying to generate 2 random numbers, add them together and have the user input match the answer, it works for lower numbers in the range(0-50) but not for higher numbers. Im relatively new to programming so any help would be great. Thanks in advance

static int randomNum(){
Random numR = new Random();
int randomNum = numR.nextInt(51);

return randomNum;  

}

public static void main(String[] args) {
    // TODO code application logic here
    
    Scanner sc = new Scanner(System.in);
    int num1 =randomNum();
    int num2 =randomNum();
    int answer =num1 num2;
    
   
    System.out.println("What is " num1 " " num2 " equal to?");
    if (sc.hasNextInt(answer))
        System.out.println("Correct");
    else
        System.out.println("Wrong");

} }

CodePudding user response:

hasNextInt(someInt), which is what you're invoking, treats the argument as the radix, totally not what you want. Even if it did what you wanted, it wouldn't consume the input - it's hasNextInt, not consumeNextInt.

You want to call sc.nextInt(), and then compare what that returned with answer.

  • Related