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.

Recommended Answers

All 4 Replies

Please give us some code. It is a lot easier then.

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:");

		try{	
                       //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)
while(looper)
{
System.out.println("Input your number: ");
input = scan.nextDouble();

doMagic(input);
looper = false;

}

Hope this helps

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.