JOptionPane input in int

I am trying to get JOptionPane to get the input and assign it int, but I am having some problems with variable types.

I am trying something like this:

Int ans = (Integer) JOptionPane.showInputDialog(frame, "Text", JOptionPane.INFORMATION_MESSAGE, null, null, "[sample text to help input]"); 

But I get:

 Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer 

Which sounds logical, I can't think of another way to do this.

Thanks in advance

+7
java int swing user-input joptionpane
source share
5 answers

Just use:

 int ans = Integer.parseInt( JOptionPane.showInputDialog(frame, "Text", JOptionPane.INFORMATION_MESSAGE, null, null, "[sample text to help input]")); 

You cannot cast String to int , but you can convert it with Integer.parseInt(string) .

+6
source share

This is because the input that the user inserts into the JOptionPane is String , and it is saved and returned as String .

Java cannot convert between strings and number on its own, you need to use certain functions, just use:

 int ans = Integer.parseInt(JOptionPane.showInputDialog(...)) 
+4
source share

Note that Integer.parseInt throws a NumberFormatException if the passed string does not contain a string with a syntax expression.

0
source share
 // sample code for addition using JOptionPane import javax.swing.JOptionPane; public class Addition { public static void main(String[] args) { String firstNumber = JOptionPane.showInputDialog("Input <First Integer>"); String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>"); int num1 = Integer.parseInt(firstNumber); int num2 = Integer.parseInt(secondNumber); int sum = num1 + num2; JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sum of two Integers", JOptionPane.PLAIN_MESSAGE); } } 
0
source share
 String String_firstNumber = JOptionPane.showInputDialog("Input Semisecond"); int Int_firstNumber = Integer.parseInt(firstNumber); 

Your Int_firstnumber contains the integer String_fristNumber .

hope this helped

0
source share

All Articles