Helpful Information
 
 
Category: Java and JSP
java codes problem

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

}}

It might be nice to know what the error was that the compiler gave you.

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

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.

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

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










privacy (GDPR)