Parsing numbers in Java

The example below takes user input and parses it. If the user types in an invalid number, an error message will be displayed.

import java.util.Scanner;
public class NumberTest {
    public static void main(String[] args) {
 
       Scanner scanner = new Scanner(System.in);
       String userInput = scanner.next();
       try {
           int i = Integer.parseInt(userInput);
           System.out.println("The number entered: " + i);
       } catch (NumberFormatException e) {
           System.out.println("Invalid user input");
       }
    }
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.