Search code examples
javaexceptiontry-catchparseint

Exeptions and parseInt


Why is it that my first method "inputNumber" returns infinite output "this is not a valid number" while the second method returns to the question "type a valid number: "

i don't understand why the method with the parseInt doesn't do the same thing... they both throw an exception and both execute the "catch".

here's my code:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("you typed the number: " + inputNumber(input));

}

public static int inputNumber(Scanner input) {
    int num = 0;
    while (num == 0) {
        System.out.print("Type a number: ");
        try {
            return input.nextInt();
        } catch (Exception e) {
            System.out.println("this is not a valid number");
        }
    }
    return num;
}

public int readNumber(Scanner input) {
    boolean running = true;
    while (running) {
        System.out.print("Write a number: ");

        try {
            int num = Integer.parseInt(input.nextLine());
            return num;
        } catch (Exception e) {
            System.out.println("this is not a valid number");
        }
    }
    return 0;
}
}

Solution

  • Please make few changes:
    1. No need of num variable in inputNumber() method,
    2. Make readNumber() method static.
    

    Also you can try this logic for inputNumber() method.

    public static int inputNumber(Scanner input) {
       System.out.print("Type a number: ");
        try {
            return input.nextInt();
        } catch (Exception e) {
            System.out.println("this is not a valid number");
        }
        return 0;
    }