Search code examples
javajava.util.scannerpatternsyntaxexception

Scanner.nextInt(x) throws PatternSyntaxException


i know im so nooby for asking but please i want to pass my midterm

one of the many questions i have a problem with is ""Write an if-else statement that assigns 20 to the variable y if the variable x is greater than 100. Otherwise, it should assign 0 to the variable y."

mine looks like this

import java.util.Scanner;

public class ifelseprac1 {

    public static void main(String[] args) {
        int y;
        int x=0;

        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter a number for x: ");
        x=keyboard.nextInt(x);

        if (x>100)
            y=20;           
        else 
            y=0;
    }
}

the error code im getting is

Configuration: ifelseprac1 - JDK version 1.8.0_25

Enter a number for x: Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 525


Solution

  • Instead of doing:

    x = keyboard.nextInt(x);
    

    Do:

    x = keyboard.nextInt();
    

    If you pass a parameter to nextInt, it's interpreted as the radix of the entered integer.

    I'm guessing that, for certain radices, the regex that Java generates to extract the integer is incorrect, but would need to debug the JDK to be sure.