gpt4 book ai didi

java - Java 中的转换问题

转载 作者:行者123 更新时间:2023-11-30 02:32:20 25 4
gpt4 key购买 nike

我收到字符串到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com