Java - 不编译错误

时间:2014-04-15 20:19:14

标签: java compiler-errors

我正在为商店做代码,这部分是为了让员工可以将手机添加到现有库存中。我无法弄清楚问题是什么,因为它不会编译并说"不兼容的类型",它标记了部分[name =" &#34 ;;                     键入=" &#34 ;;                      颜色=" &#34 ;;]

这是驱动程序类的一部分:

      //add new phone to stock
public void addPhone( ) {

     Phone phone = new Phone ( itemsId, brand, price, name, type, colour);

    Scanner scan = new Scanner(System.in);
    String itemsId; 
    String brand;
    double price;
    String name;
    String type;
    String colour;


    for (int counter=0; counter< 1; counter ++)
    {
        itemsId= "  ";
        brand="     ";
        price= 
        name= "  ";
        type="  ";
        colour=" ";

        System.out.println("Enter itemsID:   ");
        itemsId= scan.nextLine();

        System.out.println("Enter brand:     ");
        brand= scan.nextLine();

        System.out.println("Enter price:     ");
        price= scan.nextdouble();

        System.out.println("Enter name:      ");
        name= scan.nextLine();

        System.out.println("Enter type:       ");
        type= scan.nextLine();

        System.out.println("Enter colour:     ");
        colour= scan.nextLine();

    }
    phoneList.add(phone);

}

3 个答案:

答案 0 :(得分:6)

您应该为price分配一个值。

price = 0.0;
name = " ";

应该有用。

答案 1 :(得分:1)

在Java语句中,分号终止。然后

price= 
name= "  ";

被解析为price = (name = " ")。但是,String(名称赋值表达式的类型/结果)与double(价格变量的类型)不兼容,因为它们是“不兼容的类型”。

所以第一步是修复代码的解析方式

price= <put something useful here>;
name= "  ";

虽然这将“修复”直接类型错误,但程序仍然无法编译(由于未分配的局部变量和不正确的方法名称),如果编译时,如果有多个电话号码,则不会产生正确的结果将被输入 - 继续阅读。


现在,就整个程序而言:分配这些“虚拟值”,而在它们具有有意义的值之前使用变量。

考虑一下:

Scanner scan = new Scanner(System.in);

for (int counter = 0; counter < 1; counter++)
{
    // We don't need to assign defaults because these
    // variables will be assigned useful values before
    // they are used.
    double price;
    String name;
    // (other variables removed for simplicity)

    System.out.println("Enter price:     ");
    // Java is case-sensitive, make sure to use correct case.
    // The original "nextdouble" was incorrect.
    price = scan.nextDouble();

    System.out.println("Enter name:      ");
    name = scan.nextLine();

    // NOW use variables - AFTER they have useful values
    Phone phone = new Phone (.., .., price, name, .., ..);

    // Add new phone entry each loop,
    // not once at the end of all (1) loops.
    phoneList.add(phone);
}

答案 2 :(得分:1)

price = 
name = " ";

的代码相同
price = name = " ";

表示您将String值分配给double - 这些类型不兼容; 或者,删除“price =”行或在“price =”行右侧添加值:

price = 0;
name = " ";