2017-05-14 82 views
1

我收到了一個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以編譯,但它給了同樣的錯誤。 謝謝你的幫助。

+0

'total_Guests'已經是'int'了。你試圖將一個'int'解析爲一個'int',因此就是錯誤。 'parseInt'方法需要一個String參數。 –

回答

2

的問題是,你定義一個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"看起來像int12

+0

我刪除了parseInt語句,但它仍然顯示我一個錯誤。這是字符串不能轉換爲int –

+0

謝謝@AndrewTobilko它完美的作品。 –

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; 

否則會給變量不會被初始化錯誤

+0

謝謝@Shashwat我已糾正它。 –