JOptionPane Input to int

前端 未结 5 1536
面向向阳花
面向向阳花 2021-01-02 14:31

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:

相关标签:
5条回答
  • 2021-01-02 15:02

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

    0 讨论(0)
  • 2021-01-02 15:08
    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 讨论(0)
  • 2021-01-02 15:12

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

    0 讨论(0)
  • 2021-01-02 15:14
    // 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 讨论(0)
  • 2021-01-02 15:15

    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(...))
    
    0 讨论(0)
提交回复
热议问题