java - Java 中的转换问题

标签 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进行编译,但它给出了相同的错误。 感谢您的帮助。

最佳答案

问题在于您定义了 total_Guests 变量两次 (1),并尝试将 showInputDialog 方法的 String 结果分配给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 也不允许执行转换.

关于java - Java 中的转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43965155/

相关文章:

python - 从单个输入存储/添加非预定义数量的值 (Python)

c# - 为什么 float 和 int 具有如此不同的最大值,即使它们的位数相同?

java - 与数组索引相关的错误

java - 以下 JDBC/MySQL 查询有什么问题

java - 如何查找字符串中的字符总数?

c++ - 有没有更好的方法从字符串创建目录? cpp,创建目录,stringstream,字符串。

java - 我使用 Sockets 和 Netty 时遇到 "broken pipe"异常。怎么了?

java - 如何正确解码基于模式的请求结果(即 xwiki)?

python - 在 Python 中比较两组大字符串的最佳方法

java - 如何将 int[] 转换为 Integer[]?