NumberFormatException when checking if Integer is null - java

I am trying to make the user only enter a non-negative number and if the user closes the dialog the program should terminate.
Integer num = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive number"));
if (num == null)
{
System.exit(0);
}
else if (num < 0)
{
num = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive number"));
}
This code works if num is type String but not when I changed it to integer.
I get a NumberFormatException when I try to run it and the code in the if statment is dead code.

parseInt doesn't return null if passed a null/invalid string, it throws an exception, which you need to catch.
int num;
for (;;) {
String input = JOptionPane.showInputDialog("Enter a positive number");
if (input == null) System.exit(0);
try {
num = Integer.parseInt(input);
break;
} catch (NumberFormatException e) {
// continue;
}
}

The problem was that the function showInputDialog returns an empty string if exited or if the input was nothing so for fixing it you can check the input if it's empty look at this code:
num = (str.equals(""))?null:Integer.parseInt(str);
it's better to use a do{}while(); loop to get a more efficient code example:
String str;
Integer num;
do{
str = JOptionPane.showInputDialog("enter a positive number");
num = (str.equals(""))?null:Integer.parseInt(str);
if(num == null){
System.exit(0);
}
}while(num<0);

NFE - indicates that your string is not a number so you need to catch an error and make decision of what to do in case of unsuitable string, eg.
try {
if (Integer.parseInt("-123") < 0) {
// do job
}
} catch (NumberFormatException e) {
// string is not a number
// set value to default, log error, return error to users view
System.exit(9);
}

Related

how to check the else statement in if else condition

package react;
import java.util.Scanner;
public class Intputfromuser {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("enter a number to compare with number 5 ");
Scanner input= new Scanner(System.in);
int a=input.nextInt();
if(a==2)
{
System.out.println("U Have Entered The same value");
}
else if(a<2)
{
System.out.println("Ur number is Smaller than 2");
}
else if(a>2)
{
System.out.println("U Have Entered the number Greater than ");
}
else {
System.out.println("U Have Enterer Invalid Input");
}
}
}
how to get only integer from the user if the user enters any thing except integer then else statement should run
Another alternative. Be sure to read the comments in code:
public static void main(String[] args) {
/* Open a keyboard input stream. There is no need to close
this stream. The JVM will do that automatically when the
application closes. */
Scanner input = new Scanner(System.in);
String val = ""; // Used to store User input:
// User Prompt with 'quit' capability and entry validation:
while (val.isEmpty()) {
System.out.print("Enter a number to compare with number 5 (q to quit): -> ");
val = input.nextLine().trim(); // Trim in case just a whitespace(s) was entered.
// Was 'q' for quit supplied?
if (val.equalsIgnoreCase("q")) {
/* Yes...then quit. Returning out of main() effectively
closes this particular application: */
System.out.println("Quiting - Bye Bye");
return;
}
// Validate Entry:
/* Is entry a string representation of a signed or unsigned Integer
value and does the supplied value fall within the relm of an int? */
if (!val.matches("-?\\d+") || (Long.parseLong(val) < Integer.MIN_VALUE) ||
(Long.parseLong(val) > Integer.MAX_VALUE)) {
// No...Inform User and allow to try again:
System.out.println("Invalid Numerical Entry! {" + val + ") Try again..."
+ System.lineSeparator());
val = ""; // Empty variable to ensure re-loop:
}
}
// If you make it to this point in code, the User input was valid!
// Now parse the String numerical value to an int:
int a = Integer.parseInt(val);
/* At this point, there are only three usable conditions:
Equal To, Less Than, and Greater Than (validity has
already been handled within the `while` loop: */
// Equal To:
if (a == 5) {
System.out.println("You have entered The same value.");
}
// Less Than:
else if (a < 5) {
System.out.println("Your number is smaller than 5.");
}
// Greater Than:
else {
System.out.println("You have entered a number greater than 5.");
}
// DONE
}
You can also create method to collect input and make it inside loop like this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("enter a number to compare with number 5: ");
int userInput = getInteger();
if (userInput == 2)
{
System.out.println("U Have Entered The same value");
}
else if (userInput < 2)
{
System.out.println("Ur number is Smaller than 2");
}
else {
System.out.println("U Have Entered the number Greater than 2");
}
}
static int getInteger() {
boolean correct = false;
Scanner input = new Scanner(System.in);
int userInput = 0;
do {
try {
userInput = input.nextInt();
correct = true;
} catch (Exception e) {
System.out.println("Incorrect input");
System.out.println("Please try again: ");
} finally {
input.nextLine();
}
}
while (!correct);
input.close();
return userInput;
}
}
Important note with scanner.nextInt() or scanner.nextDouble()
you need to call scanner.nextLine() after that to clear input. Otherwise you will end up with endless loop.
Use input.nextLine() instead and parse it to a String.
To avoid a ParseException, surround it by using a try { ... } catch() { ... } block.
In the catch block you can e.g. print a message informing the user of the wrong input.
public static void main(String[] args) {
System.out.println("enter a number to compare with number 5 ");
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
try {
int option = Integer.parseInt(userInput);
if (option == 2)
{
System.out.println("U Have Entered The same value");
}
else if (option < 2)
{
System.out.println("Ur number is Smaller than 2");
}
else if (option > 2)
{
System.out.println("U Have Entered the number Greater than 2");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input!");
}
}
Hope this sort of helped!

How can I make the code catch the error when the input provided is not a number?

The program checks the user input and determines if it's positive or negative.
How can I catch the error when the user provides an invalid input (non-integer) such as "444h" or "ibi".
I was thinking the final else statement would catch the exception but it does not.
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = scan.nextInt();
scan.close();
if(num > 0)
{
System.out.println(num+" is positive");
}
else if(num < 0)
{
System.out.println(num+" is negative");
}
else if(num == 0)
{
System.out.println(num+" is neither positive nor negative");
}
else
{
System.out.println(num+" must be an integer");
}
}
}
I expect the program to catch the exception and prompt input of a valid integer
Simply wrap your code in a try..catch block.
Full code:
import java.util.Scanner;
import java.util.InputMismatchException;
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
Scanner scan = new Scanner(System.in);
System.out.print("Enter any number: ");
try {
int num = scan.nextInt();
if (num > 0) {
System.out.println(num + " is positive");
} else if (num < 0) {
System.out.println(num + " is negative");
} else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
} catch (InputMismatchException e) {
System.out.println("Error: Value Must be an integer");
}
scan.close();
}
}
Good luck :)
int num = 0;
try{
num =input.nextInt();
}catch(InputMismatchException ex) {
System.out.println("Enter Integer Value Only");
}
You have to write int num = scan.nextInt(); this statement inside try block if you get non-integer value from input then InputMismatchException will arise then catch block will executed.
First off, don't close the Scanner if you plan on using it again during the operation of your application. Once you close it, you will need to restart your application in order to use it again.
As already mentioned, you could utilize a try/catch on the Scanner#nextInt() method:
Scanner scan = new Scanner(System.in);
int num = 0;
boolean isValid = false;
while (!isValid) {
System.out.print("Enter any number: ");
try {
num = scan.nextInt();
isValid = true;
}
catch (InputMismatchException ex) {
System.out.println("You must supply a integer value");
isValid = false;
scan.nextLine(); // Empty buffer
}
}
if (num > 0) {
System.out.println(num + " is positive");
}
else if (num < 0) {
System.out.println(num + " is negative");
}
else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
Or you could use the Scanner#nextLine() method instead which accepts string:
Scanner scan = new Scanner(System.in);
String strgNum = "";
boolean isValid = false;
while (!isValid) {
System.out.print("Enter any Integer value: ");
strgNum = scan.nextLine();
/* See if a signed or unsigned integer value was supplied.
RegEx is used with the String#matches() method for this.
Use this RegEx: "-?\\d+(\\.\\d+)?" if you want to allow
the User to enter a signed or unsigned Integer, Long,
float, or double values. */
if (!strgNum.matches("-?\\d+")) {
System.out.println("You must supply a numerical value (no alpha characters allowed)!");
continue;
}
isValid = true; // set to true so as to exit loop
}
int num = Integer.parseInt(strgNum); // Convert string numerical value to Integer
/* Uncomment the below line if you use the other RegEx. You would have to also
comment out the above line as well. */
// double num = Double.parseDouble(strgNum); // Convert string numerical value to double
if (num > 0) {
System.out.println(num + " is positive");
}
else if (num < 0) {
System.out.println(num + " is negative");
}
else if (num == 0) {
System.out.println(num + " is neither positive nor negative");
}
Use regex to check if input is a number
import java.util.regex.*;
Pattern.matches("[0-9]+", "123"); // this will return a boolean

Endless loop with try and catch JAVA

so what I am trying to do is have the user input a valid coordinate in a matrix, that is an INT which is greater than -1,
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
while (((coordinates[1]<0)||(coordinates[1]>C)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
the problem is that it loops endlessly after entering a not valid input
int R is the size of the row
int C is the size of the collumn
Your problem is that you're not handling the error you're catching.
If you'll provide wrong format of number for the nextInt() method, then the InputMismatchException will be thrown. Then because the catch does nothing, the loop will continue (start from begining) and the scanner will read the same incorrect value, and so on...
So instead of this:
catch (InputMismatchException e) {
}
Try this:
catch (InputMismatchException e) {
System.out.println("Wrong number entered.");
scanner.nextLine();
}
This way you'll force scanner to move past the last incorrect input.
EDIT:
You're loop is also broken because you do break after reading the input. In that case if you'll put the negative number you'll break as well and won't check the loop condition. Remove the break statement and it will work as expected:
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
EDIT2:
public static void main(final String args[])
{
int maxRowsNumber = 10;
int maxColsNumber = 10;
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>maxRowsNumber)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
while (((coordinates[1]<0)||(coordinates[1]>maxColsNumber)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
System.out.println("Inserted RowsNumber: " + coordinates[0]);
System.out.println("Inserted RowsNumber: " + coordinates[1]);
}
Output:
Please enter a valid row number: 11
Please enter a valid row number: 22
Please enter a valid row number: 10
Please enter a valid col number: 11
Please enter a valid col number: 2
Inserted RowsNumber: 10
Inserted RowsNumber: 2
If by "not valid input" you mean "not any kind of integer", then your scanner will fail each time it tries to read another integer, so you'll hit your catch, and do nothing to stop the loop. Maybe you intended to set check to false in such circumstances? Or maybe you meant to put the break in each catch?
Using a break when a valid integer is read isn't right, because it might be a negative integer, which your loop guard says you don't want.
This is basically the same as what your doing, I just tried to improve it a little bit by removing hardcoded values, made variables more descriptive, and included input validations.
final int ROW = 0;
final int COL = 1;
int coordinates[] = new int[2];
coordinates[ROW] = -1;
coordinates[COL] = -1;
boolean isInputValid = true;
Scanner scanner = new Scanner(System.in);
do {
try {
System.out.print("Please enter a valid row number:\t");
coordinates[ROW] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false; //if the input is not int
}
} while (!isInputValid && (coordinates[ROW] < 0) //do this until the input is an int
|| (coordinates[ROW] > R)); //and it's also not less than 0 or greater than R
//same logic applies here
do {
try {
System.out.print("Please enter a valid col number:\t");
coordinates[COL] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false;
}
} while (!isInputValid && (coordinates[COL] < 0)
|| (coordinates[COL] > C));
Hope this helps.

Exception in do while loop

I have this piece of code:
do {
try {
input = sc.nextInt();
}
catch(Exception e) {
System.out.println("Wrong input");
sc.nextLine();
}
}
while (input < 1 || input > 4);
Right now, if I input 'abcd' instead of integer 1-4, it gives message "Wrong Input" and the program loops, how can I make it so that it also gives "Wrong Input" when I entered integer that doesn't fulfill the boolean (input < 1 || input >4)?
So that if I entered 5, it will also give me "Wrong Input".
Add this:
if(input < 1 || input > 4) {
System.out.println("Wrong input");
}
after input = sc.nextInt();
As of now, your try-catch block is checking if input is an int type. The do-while loop is checking input after it has been entered, so it is useless. The condition must be checked after the user enters what he/she wants. This should fix it:
do
{
try
{
input = sc.nextInt();
if(input < 1 || input > 4) // check condition here.
{
System.out.println("Wrong input");
}
}
catch(Exception e)
{
System.out.println("Expected input to be an int. Try again."); // tell user that input must be an integer.
sc.nextLine();
}
} while (input < 1 || input > 4);
You can also do this:
while (true) {
try {
input = sc.nextInt();
if (input >= 1 && input <= 4) {
break;
}
} catch (Exception e) {
System.out.println("Wrong input");
}
sc.nextLine();
}

Missing return error

/**
* Read a positive integer and return its value
* #param the prompt to be shown to the user
*/
public static int readPositiveInteger(String prompt)
{
System.out.println (prompt);
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
boolean positive = false;
if (scan.hasNextInt() && positive == false)
{
int input = scan.nextInt();
if (input > 0)
{
positive = true;
{
return input;
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
}
I'm trying to make it so the user can't insert 0 or a negative number. However I don't think my logic is correct as I'm getting a missing return error. Can anyone help?
Thanks!
The if should be a while:
while (scan.hasNextInt() && positive == false)
{
int input = scan.nextInt();
if (input > 0)
{
positive = true;
{
return input;
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
Really, there's no need of keeping the positive boolean, since the moment it passes
if (input > 0)
it immediately returns, without any further checks on the boolean.
Your method signature is as follows:
public static int readPositiveInteger(String prompt)
However, you never return an integer. You have two choices:
Add something like return 0; to the end of your method
Change static int to static void.
The first is the better option, I think, since you want to return the integer that was read. If none is read, you can tell the program a 0 was there.
The best option, though, is to modify your if statement to use a while loop, and return something only when the user has inputted something.
As mentioned by others here, your outer if statement should be a while loop:
while (scan.hasNextInt() && positive == false)
{
...
}
Also, you've only one return statement written in an if statement. If simply converting the above mentioned if statement to a while loop doesn't help, try return 0 after your while loop.
The java compiler (and others as well) doesn't understand the semantics of code. It can only check for a correct syntax. So, in your case, it might be concerned that the return command might never be reached. A return 0 at the end of your function would solve that (despite that return 0 will never be reached).
public static int readPositiveInteger(String prompt)
{
System.out.println (prompt);
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
boolean positive = false;
int input;
if (scan.hasNextInt() && positive == false)
{
input = scan.nextInt();
if (input > 0)
{
positive = true;
{
return input;
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
return input;
}
All paths of your method should return something since you define it as
public static int readPositiveInteger(String prompt)
Looks like you are expecting your code to be in a while loop or something?
As it stands it can "run off the bottom" - and like the error says, there is no return (which is required).
You need a while loop. In pseudo code:
While true (ie loop forever)
Ask for input
If input ok return it
You have to add a return statement in the else block otherwise your code wont compile
your method expects a return statement in the else block
else
{
System.out.println ("Bad input enter an integer.");
positive = false;
scan.nextLine();
return 0;//your missing return statement
}
}
What you have to do is add return input; in the end of the method that is
public static int readPositiveInteger(String prompt) {
System.out.println(prompt);
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
boolean positive = false;
if (scan.hasNextInt() && positive == false) {
int input = scan.nextInt();
if (input > 0) {
positive = true;
{
return input;
}
} else {
System.out.println("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
}
else {
System.out.println("Bad input enter an integer.");
positive = false;
scan.nextLine();
}
return 0;
}
This function will work perfectly for you
public static int readPositiveInteger(String prompt) {
System.out.println(prompt);
System.out.println("Enter an integer");
Scanner scan = new Scanner(System.in);
boolean positive = false;
int input = 0;
while (input <= 0) {
System.out.println("please enter a number greater then 0");
input = scan.nextInt();
}
return input;
}
public static int readPositiveInteger()
{
return int_type;
}
has the return type as int so you should return the integer values in function.

Categories

Resources