Ok now suppose i have some code and there is a point where the user is asked to input some value into showInputDialog...and then the user must input a String value, but if the user inputs an integer value, the program crashes...please help me and explain me how can i check for the String/Integer value and display a message like "Invalid Input" instead of the program crashing. Thanks.

7 Years
Discussion Span
Last Post by Cort3z

Well, the showInputDialog method returns a String, So there wont be any problem with this. But if you want to know whether the value the user typed is a number or not, you can use a try and catch as follow:

//This method returns a String.
String o = JOptionPane.showInputDialog("Insert a value:");

                       //You can try converting the value to a double, so that you can know if it is a numeric value.
			double l = Double.parseDouble(o);
		}catch(NumberFormatException number)
			//if the value is not a numeric value then you reach this point, here you can tell the user to use a numeric value.

                     JOptionPane.showMessageDialog(null, "Please type a numeric value.");

Instead of using "parseDouble" you should use scanner and write something like this:
(if you want the program to get a double value)

import java.util.Scanner;

boolean looper = true;
Double input;
Scanner scan = new Scanner(System.in)
System.out.println("Input your number: ");
input = scan.nextDouble();

looper = false;


Hope this helps

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.