How do i check the input is an integer in java [duplicate] - java

This question already has answers here:
How to loop user input until an integer is inputted?
(5 answers)
Closed 3 years ago.
In my program I want an integer input by the user. I want an error message to be show when user inputs a value which is not an integer.
And How can I do this in loop. i am just a beginner please help me.
//code that i already try
Scanner input = new Scanner(System.in);
int age;
String AGE ;
System.out.print("\nEnter Age : ");
AGE = input.nextLine();
try{
age = Integer.parseInt(AGE);
}catch (NumberFormatException ex){
System.out.print("Invalid input " + AGE + " is not a number");
}

You use an while loop and break on sucess
int age;
while (true) { // wil break on sucess
Scanner input = new Scanner(System.in);
System.out.print("\nEnter Age : ");
String AGE = input.nextLine();
try{
age = Integer.parseInt(AGE);
break;
}catch (NumberFormatException ex){
System.out.print("Invalid input " + AGE + " is not a number");
}
}

This is the better way to check user input is integer or Not -
public static void onlyInteger() {
int myInt = 0;
System.out.println(" Please enter Integer");
do {
while (!input.hasNextInt()){
System.out.println(" Please enter valid Integer :");
input.next();
}
myInt = input.nextInt();
}while (myInt <= 0);
}
Hope this will help.

If you are trying to capture the age input as an integer, you would not need the integer array as such
'int age [] = new int [100];'
You can use Scanner's nextInt() method to capture integer input.
This will throw InputMismatchException exception in case the input is not an integer.Try below code.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Age: ");
try {
int number = input.nextInt();
System.out.println("Age entered " + number);
} catch (InputMismatchException e) {
System.out.println("Incorrect Input for Age.Please enter integer Integer value");
}
}

To check the input is an integer or any number :
Step 1 is to Read the input as Java Object, then
Object o = new Integer(33);// or can be new Float(33.33)...
if(o instanceof Number) {
System.out.println(o +" is number");// do your thing here
}
The abstract class Number is the superclass of platform classes representing numeric values that are convertible to the primitive types byte, double, float, int, long, and short.
JavaDoc Number

Related

types cannot be converted when validating the users input for an integer

I am trying to validate a user's input and check if the inputted number is an integer. Id like to throw them an error message if the number isn't an integer. I am getting stuck on the line Integer.parseInt(number); Any suggestions would be very appreciated.
import java.util.Scanner;
public class Sums {
public static int number;
public static void main(String[] args) {
int evenSum, oddSum = 0;
int posInt;
Scanner input = new Scanner(System.in);
System.out.println("Enter a postitive integer: ");
int number = input.nextInt();
try {
Integer.parseInt(number);
System.out.println("Value entered is " + number);
} catch (NumberFormatException e) {
System.out.println(number + " is not an integer.");
}
}
}
I have changed the int number = input.nextInt(); to String number = input.next(); and it works.
The issue here is that when you call Integer.parseInt(number) you are trying to parse the variable number which is an int and not a String. This means that you are doing the error checking on a conversion from an int to an Integer and not a String to an Integer.
To fix this, input a string instead of a number, then perform the conversion on the string, not the number.
...
public static void main(String[] args) {
int myNumber;
Scanner input = new Scanner(System.in);
System.out.println("Enter a postitive integer: ");
String numberString = input.nextLine();
try {
myNumber = Integer.parseInt(number);
System.out.println("Value entered is " + myNumber);
// do what you want with the number
} catch (NumberFormatException e) {
System.out.println(numberString + " is not an integer.");
}
}
...
You don't need explicitly to convert your number to an integer, Scanner.nextInt() already does that for you, i.e. Scanner.nextInt() scans the next token of the input as an int. So just remove the line "int number = input.nextInt();" from your code. In general, Integer.parseInt() is preferable when you want to convert a String representation of an Integer value as a signed decimal integer. For instance, if you would have used Scanner.nextLine() instead of Scanner.nextInt(), then it makes more sense to convert it to a signed decimal integer if you want to perform subsequent operations using that integer value.
int number = input.nextInt();
The variable number is already an int, that is why you can not hand it over to the method. The method requires a String.
If you want to use the method like you did, you should use
input.next()
as argument because it returns the input as String and initialize number within the try block, e.g.
public static void main(String[] args) {
int evenSum, oddSum = 0;
int posInt;
System.out.println("Enter a postitive integer: ");
Scanner input = new Scanner(System.in);
try {
number = Integer.parseInt(input.next());
System.out.println("Value entered is " + number);
} catch (NumberFormatException e) {
System.out.println("Not an integer.");
}
}
Bug here is int number = input.nextInt();
When you want to convert a String to a primitive datatype we use class.parseXXX(String)
You see I have written String in the function .parseXXX(String) Cause it takes String as a parameter and nothing else
So lets read your code
Integer.parseInt(number);
Here its .parseXXX(int) and clearly its not matching .parseXXX(String)
So in order to give String as parameter, you have accept String as input from user.
Replace this int number = input.nextInt(); with String number = input.next();
So now below code is valid cause its in .parseXXX(String)
Integer.parseInt(number);
Changed code:
int evenSum, oddSum = 0;
int posInt;
Scanner input = new Scanner(System.in);
System.out.println("Enter a postitive integer: ");
String number = input.next(); // <-- Changed
try {
Integer.parseInt(number);
System.out.println("Value entered is " + number);
} catch (NumberFormatException e) {
System.out.println(number + " is not an integer.");
}

InputMismatchException for String input into integer field

I am having trouble with entering non-integers into an integer field. I am only taking precautions so that if another person uses/works on my program they don't get this InputMismatchException.
When I enter a non-digit character into the input variable, I get the above error. Is there any way to compensate for this like one could do for a NullPointerException when it comes to strings?
This code is redacted just to include the relevant portions causing the problem.
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
input = user_input.nextInt();
System.out.println("You are: " +input+ " years old");
}
}
You can use an if statement to check if user_input hasNextInt(). If the input is an integer, then set input equal to user_input.nextInt(). Otherwise, display a message stating that the input is invalid. This should prevent exceptions.
System.out.println("What is your age? : ");
if(user_input.hasNextInt()) {
input = user_input.nextInt();
}
else {
System.out.println("That is not an integer.");
}
Here is some more information about hasNextInt() from Javadocs.
On a side note, variable names in Java should follow the lowerMixedCase convention. For example, user_input should be changed to userInput.
You can add a try-catch block:
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
try{
input = user_input.nextInt();
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
}
System.out.println("You are: " +input+ " years old");
}
}
If you want to provide the user to enter another int you can create a boolean variable and make a do-while loop to repeat it. As follows:
boolean end = false;
//code
do
{
try{
input = user_input.nextInt();
end = true;
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
end = false;
System.out.println("Try again");
input.nextLine();
}
}while(end == false);
This is a try-catch block. You need to use this if you want to be sure of not making the program-flow stop.
try {
input = user_input.nextInt();
}
catch (InputMismatchException exception) { //here you can catch that exception, so program will not stop
System.out.println("Integers only, please."); //this is a comment
scanner.nextLine(); //gives a possibility to try giving an input again
}
Test using hasNextInt().
Scanner user_input = new Scanner(System.in);
System.out.println("What is your age?");
if (user_input.hasNextInt()) {
int input = user_input.nextInt();
System.out.println("You are " + input + " years old");
} else {
System.out.println("You are a baby");
}
Use Scanner's next() method to get data instead of using nextInt(). Then parse it to integer using int input = Integer.parseInt(inputString);
parseInt() method throws NumberFormatException if it is not int, which you can handle accordingly.

input a number on scanner

I am trying to create a simple Java program where the user should input his age. If the user entered for example a letter instead of a number, he will get a message.
What I would like to do is that in addition to the message the user should be asked for another input and that input will be checked again to see if it is a number.
Can anyone know how can I achieve that?
System.out.println("2 - Set The Age");
Scanner b = new Scanner(System.in);
if (b.hasNextDouble()) {
double lage = b.nextDouble();
setAge(lage);
addEmployeeMenu();
} else {
System.out.println("You should type only numbers!");
}
You can use a while loop like this
Scanner b = new Scanner(System.in);
double lage;
while (true) {
System.out.println("2 - Set The Age");
if(b.hasNextDouble()){
lage = b.nextDouble();
break;
}else b.nextLine();
}
The point is, get your number and check it inside a while loop, repeat as long as the input is not correct
You can also use NumberFormatException:
while (true) {
System.out.println("Set the age: ");
String input = sc.next();
try {
int x = Integer.parseInt(input);
System.out.println("Your input '" + x + "' is a integer");
break;
} catch (NumberFormatException nFE) {
System.out.println("Not an Integer");
}
}

How do I check to see if the input is an integer?

Very Frustrated at my professor, because she did not teach try and catch concepts, neither did she teach us about throw exceptions either, so it is very difficult for me to do this program. The objective is to make a program where the user is asked to input an integer that prints "Hello World" that many times of the integer. The problem is I cannot check to make sure the user input is an integer. For instance, if the user chose to type a character or a double, how do I implement that into my code? And I cannot use throw exceptions or try and catch because we did not learn them yet.Thanks guys!!!
import java.util.Scanner;
public class PrintHelloWorld
{
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
int number;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
number = scan.nextInt();
System.out.print("Your integer is " + number);
int remainder = number%1;
int counts = 0;
if( number>0 && remainder == 0)
{
while(counts <= number)
{
System.out.println("Hello World!");
counts++;
}
}
else
System.out.print("Wrong, choose an integer!");
}
}
scan.hasNextInt()
will check to see if the next value in the input stream is an integer.
as such:
int number = -1;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
if (scan.hasNextInt()) number = scan.nextInt();
if (number != -1) System.out.print("Your integer is " + number);
You can use a loop and validate the input with a regex, like this:
Scanner scan = new Scanner(System.in);
String input = null;
while (true) {
input = scan.nextLine();
if (input.matches("\\d+")) {
break;
}
System.out.println("Invalid input, please enter an integer!");
}
int number = Integer.parseInt(input);
This will keep asking for input until a valid integer is entered.
And I cannot use throw exceptions or try and catch because we did not
learn them yet.
For a first attempt, you could create a method that accepts a String as parameter. You will loop through all the chars of this String and check if each char is a digit. While this method returns false, re-ask the user for a new input.
Then use Integer.valueOf to get the int value..
public static boolean isNumber(String input)
You will have to use sc.nextLine() to get the input
The method Character.isDigit and toCharArray() will be useful

Using while loop as input validation [duplicate]

This question already has answers here:
Determine if a String is an Integer in Java [duplicate]
(9 answers)
user input check int only
(4 answers)
Closed 9 years ago.
I'm trying to use while loop to ask the user to reenter if the input is not an integer
for eg. input being any float or string
int input;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the number of miles: ");
input = scan.nextInt();
while (input == int) // This is where the problem is
{
System.out.print("Invalid input. Please reenter: ");
input = scan.nextInt();
}
I can't think of a way to do this. I've just been introduced to java
The issue here is that scan.nextInt() will actually throw an InputMismatchException if the input cannot be parsed as an int.
Consider this as an alternative:
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of miles: ");
int input;
while (true) {
try {
input = scan.nextInt();
break;
}
catch (InputMismatchException e) {
System.out.print("Invalid input. Please reenter: ");
scan.nextLine();
}
}
System.out.println("you entered: " + input);
The javadocs say that the method throws a InputMismatchException if the input doesn;t match the Integer regex. Perhaps this is what you need?
So...
int input = -1;
while(input < 0) {
try {
input = scan.nextInt();
} catch(InputMismatchException e) {
System.out.print("Invalid input. Please reenter: ");
}
}
as an example.

Categories

Resources