Click here to Skip to main content
15,884,353 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi this is Java question,
From this code, I am trying to accept a user input and store it in an integer variable. Then, I am trying to validate the variable to check if the input is an integer or not. If the input is an integer, you print "The input is an integer".

However, if the user input is not of integer type, then we prompt the user to enter the number again until the user inputs an integer. I have tried the following code below using try and catch:
Please help.

What I have tried:

import java.util.*;

public class studentExpensesUOWD {
	//Used to define a new object that would contain all input functions.
	static Scanner console = new Scanner (System.in);
	
	public static void main(String[] args) {
		
		int number;
		boolean done = false;
		do
		{
			try
			{
				System.out.print("Enter a number: ");
				number = console.nextInt();
				done = true;
		}
			catch (InputMismatchException e)
			{
				System.out.println("Invalid integer input");
			}
		} while (done == false);
			
			
		System.out.println("Integer Value Accepted");
		System.exit(0);
	}

}
Posted
Updated 14-Jun-20 23:12pm

Use hasNextInt[^] of the Scanner class.
An example Java.util.Scanner.hasNextInt() Method Example[^]
 
Share this answer
 
Comments
Member 13494728 31-Oct-17 0:27am    
I do not know how to use that method.
Could you please provide a small example?
CPallini 31-Oct-17 6:05am    
5.
Peter Leow 1-Nov-17 10:38am    
Thank you, CPallini.
You need to add
console.next();
after
System.out.println("Invalid integer input");


Refer on java - Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()? - Stack Overflow[^]
 
Share this answer
 
System.out.print("Enter a number: ");
do {
  try {
	if ( number.hasNextInt() ) {
            number = console.nextInt();
	    done = true;
        }
       } catch (InputMismatchException e) {
          System.out.println("Invalid integer input");
          System.out.print("Enter a number: ");
      } 
   } while (done == false);

System.out.println("Integer Value Accepted");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900