...

View Full Version : java codes problem



0810
10-09-2002, 01:30 AM
Hi could you help me this scirpt.
I got a error I don't know why.

i can't run this code





import javax.swing.JOptionPane;
public class ito
{
public static void main(String[] args)
{

int number = JOptionPane.showInputDialog("Enter number: ");
switch(number)
{
case 0:
System.out.println("you typed zero");
break;
case 1:
System.out.println("you typed one");
break;
default:
System.out.println("you didn't type zero or one");
break;


}

System.exit(0);

}}

Spookster
10-09-2002, 02:02 AM
It might be nice to know what the error was that the compiler gave you.

0810
10-09-2002, 04:58 AM
Here is error I get it



A:\ito.java:7: Incompatible type for declaration. Can't convert java.lang.String to int.
int number = JOptionPane.showInputDialog("Enter number: ");
^
1 error

Tool completed with exit code 1


could you help me

Thanks

Spookster
10-09-2002, 05:08 AM
The error message says it all. The showInputDialog method returns a string so you cannot assign it to an integer datatype. What you would need to do is convert it to an integer first.




import javax.swing.JOptionPane;
public class ito
{
public static void main(String[] args)
{

String input = JOptionPane.showInputDialog("Enter number: ");

int number = Integer.parseInt(input);

switch(number)
{
case 0:
System.out.println("you typed zero");
break;
case 1:
System.out.println("you typed one");
break;
default:
System.out.println("you didn't type zero or one");
break;

}

System.exit(0);

}}



Of course it would probably be a good idea to add in some code to validate the input to ensure it actually is a number that they entered and also the required number of digits.

ahosang
10-09-2002, 06:03 PM
You are forced to check for Number by the compiler:
try {
int number=Integer.parseInt(input);
} catch (NumberFormatException nfe) {
//code to execute if not a number
}

You must use try/catch block or else declare your main method to throw an Exception

Bob White
03-23-2007, 04:43 PM
I have a HTML page that I need to insert ads, but the ads are in javascript and not doing well , guess i need help



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum