java JOptionPane输入到整数

gzszwxb4  于 2022-12-25  发布在  Java
关注(0)|答案(6)|浏览(166)

我尝试让JOptionPane获取一个input并将其赋给一个int,但是我在变量类型方面遇到了一些问题。
我在尝试这样的方法:

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

但我得到了:

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

这听起来很合乎逻辑,但我想不出另一种方法来实现这一点。

irtuqstp

irtuqstp1#

只需用途:

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

不能将String强制转换为int,但可以使用Integer.parseInt(string)进行转换。

8fsztsew

8fsztsew2#

这是因为用户插入到JOptionPane中的输入是String,并且它作为String存储和返回。
Java不能自己在字符串和数字之间转换,你必须使用特定的函数,只要用途:

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

htrmnn0y3#

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 ");
}
}
j2datikz

j2datikz4#

请注意,如果传递的字符串不包含可解析的字符串,Integer.parseInt将抛出NumberFormatException。

u4dcyp6a

u4dcyp6a5#

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

bmvo0sr56#

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

现在,您的Int_firstnumber包含String_fristNumber的整数值。
希望能有所帮助

相关问题