开发者

JOptionPane Input to int

I am trying to make a JOptionPane get an input and assign it to an int but I am getting some problems with the 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 am getting:

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

Which sounds logical yet, I cannot think of another way to make this happen.


Simply use:

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

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


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

Java cannot convert between strings and number by itself, you have to use specific functions, just use:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))


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

       String name = JOptionPane.showInputDialog("Enter First integer");

      String name2 = JOptionPane.showInputDialog("Enter second integer");

       JOptionPane.showMessageDialog(null, "The first inputted is 89 and the second 
    integers inputted is 45" );

    int number =Integer.parseInt(JOptionPane.showInputDialog(null, "89+45 = "));

    JOptionPane.showMessageDialog(null, "Question Message", "Title",
   JOptionPane.QUESTION_MESSAGE);

    int option = JOptionPane.showConfirmDialog(null, "Do you want to continue? ");
    JOptionPane.showMessageDialog(null, "Your choice is "+option);

    JOptionPane.showMessageDialog(null, " The sum of the two integers is : 134 ");
}
}


Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.


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


String String_firstNumber = JOptionPane.showInputDialog("Input  Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);

Now your Int_firstnumber contains integer value of String_fristNumber.

hope it helped

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜