Java中的转换问题

时间:2017-05-14 14:39:18

标签: java string int type-conversion

我收到一个字符串到int转换错误。我试图在这里寻求答案:How to convert a String to an int in Java? 但我无法解决这个问题。 我的代码如下:

import javax.swing.JOptionPane;
public class CarlysEventPrice
{
    public static void main(String[] args)
    {
    int total_Guests, total_Price, price_Per_Guest;
    total_Guests = JOptionPane.showInputDialog(null, "Please input the number of guests");
    int total_Guests = Integer.parseInt(total_Guests);
    total_Price = price_Per_Guest * total_Guests;
    JOptionPane.showMessageDialog(null,
                                  "************************************************\n" +
                                  "* Carly's makes the food that makes it a party *\n" +
                                  "************************************************\n");
    JOptionPane.showMessageDialog(null,
                                  "The total guests are " +total_Guests+ "\n" +
                                  "The price per guest is " +price_Per_Guest+ "\n" +
                                  "The total price is " +total_Price);
    boolean large_Event = (total_Guests >= 50);
    JOptionPane.showMessageDialog(null,
                                  "Is this job classified as a large event: " +large_Event);      

    }
}

我的代码显示此错误:

CarlysEventPrice.java:10: error: incompatible types: String cannot be converted to int
      total_Guests = JOptionPane.showInputDialog(null, "Please input the number of guests");
                                                ^
CarlysEventPrice.java:11: error: variable total_Guests is already defined in method main(String[])
        int total_Guests = Integer.parseInt(total_Guests);
            ^
CarlysEventPrice.java:11: error: incompatible types: int cannot be converted to String
        int total_Guests = Integer.parseInt(total_Guests);
                                            ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output

我正在使用jGrasp进行编程,我也尝试使用cmd进行编译,但它给出了同样的错误。 谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

问题是您定义了total_Guests变量两次(1),并尝试将String方法的showInputDialog结果分配给int变量(2)

实现您真正想要的目标:

String input = JOptionPane.showInputDialog(null, "--/--");
int totalGuests = Integer.parseInt(input);

查看showInputDialog方法声明:

String showInputDialog(Component parentComponent, Object message)
^^^

您应该理解Stringint(或Integer包装器)是完全不同的数据类型,并且像Java这样的静态类型语言是不允许的即使String "12"看起来像int 12,也会执行转换。

答案 1 :(得分:0)

1. total_Guestsint,而非StringInteger#parseInt需要String。 2.您声明totalGuest两次。尝试

total_Guests = Integer.parseInt(JOptionPane.showInputDialog(null, "Message"));

另外,给price_Per_Guest一些初始值,比如

int total_Guests, total_Price, price_Per_Guest = 5;

或者它会给变量未初始化错误