Please, I need your help. Whenever I tried to run the below program, it will say incompatible types, String cannot be converted to Integer.
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String[] args)
{
String num1 = (Integer)JOptionPane.showInputDialog("Enter num1");
String num2 = (Integer)JOptionPane.showInputDialog("Enter num2");
String sum =
(Integer)String.format("The sum is: %d", (num1 + num2));
JOptionPane.showMessageDialog(null, sum);
}
}
To expound on the other answers and show the code, here is what you need to make it work:
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String[] args)
{
int num1 = Integer.parseInt(JOptionPane.showInputDialog("Enter num1"));
int num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter num2"));
String sum = String.format("The sum is: %d", (num1 + num2));
JOptionPane.showMessageDialog(null, sum);
}
}
You want to take the input from the JOptionPanes as an int
s then add them and put the result in a string
, not cast a string
to an int
.
NOTE: I wrote this on my mobile, so I'll compile and run it when I get home, but above is the general idea.
Your best bet is to take an int
in the first place.
int num1 = Integer.parseInt(JOptionPane
...
And you can either do the same with the output, or parse it again.
Its because your typecasting a String to an Integer and trying to store it in a String.
Remove (Integer) from the statement to get rid of that error.
Try this
int num1 = Integer.valueOf(JOptionPane.showInputDialog("Enter num1"));
int num2 = Integer.valueOf(JOptionPane.showInputDialog("Enter num2"));
String sum = String.format("The sum is: %d", (num1 + num2));
JOptionPane.showMessageDialog(null, sum);
It's seems you want, something like this:
public static void main(String[] args) {
Integer num1 = Integer.parseInt(JOptionPane.showInputDialog("Enter num1"));
Integer num2 = Integer.parseInt(JOptionPane.showInputDialog("Enter num2"));
String sum = String.format("The sum is: %d", (num1 + num2));
JOptionPane.showMessageDialog(null, sum);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.