0

could you please help me to make this program to get a correct number? The program should check the input type, it should be int. Also, the program should check that the value is from 1 to 10. If these conditions are true, the value should be assigned to correctNumber. So far I came up to this piece of code but I have difficulties in making it work properly.

System.out.println("Enter a number from 1 to 10:");
    Scanner scanner = new Scanner(System.in);
    while (!scanner.hasNextInt() || !isCorrectNumber(scanner.nextInt())) {
                System.out.println("Incorrect input!");
                scanner.next();
            }
            int correctNumber = scanner.nextInt();
    
        }
    private static boolean isCorrectNumber(int n) {
        return size >= 1 && size <= 10;
    }
Alena
  • 1
  • 2
  • Does this answer your question? [How to get the user input in Java?](https://stackoverflow.com/questions/5287538/how-to-get-the-user-input-in-java) – pringi Feb 07 '22 at 10:45
  • 2
    You are asking twice for user input. (scanner.nextInt) – pringi Feb 07 '22 at 10:46

1 Answers1

0

You are asking for input 2 times in your while condition Use a variable to save the input and then work with that

public static void main(String[] args) throws IOException {
    
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    
    String x = input.readLine();
    while (!isInt(x)) {
        x = input.readLine();
    }
    System.out.println(x);
}

I ask for input, i get a String, now i have to check if this string can be a number. For that i've created a boolean function isInt(String) Takes the String and returns if it can be a number.

public static boolean isInt(String str) {//function that checks if String can be parsed into an integer
    try {
        Integer.parseInt(str);
        return true;
    }catch (NumberFormatException e) {
        return false;
    }
}

I hope i've been helpfull

AlexM28
  • 71
  • 2