我收到了一個int轉換錯誤的字符串。我試圖在這裏尋找答案:How to convert a String to an int in Java? 但我無法解決問題。 我的代碼如下: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'已經是'int'了。你試圖將一個'int'解析爲一個'int',因此就是錯誤。 'parseInt'方法需要一個String參數。 –