2017-05-14 111 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我已纠正它。 –