在字符串中打印整数时出错

时间:2018-12-30 16:45:18

标签: java

我是Java的新手,正在读一本书,其中包含以下代码...

class Vehicle {
    int passengers;
    int fuelcap;
    int mpg;

    int range() {
        return mpg * fuelcap;
    }

    double fuelneeded(int miles) {
        return (double) miles / mpg;
    }
}

class TwoVehicles {
    public static void main(String args[]) {
        Vehicle minivan = new Vehicle();
        Vehicle sportscar = new Vehicle();
        double gallons;
        int dist = 252;

        minivan.passengers = 7;
        minivan.fuelcap = 16;
        minivan.mpg = 21;

        sportscar.passengers = 2;
        sportscar.fuelcap = 14;
        sportscar.mpg = 12;

        gallons = minivan.fuelneeded(dist);
        System.out.println("To go ", + dist + " miles minivan needs " + gallons + " gallons of fuel.");

        gallons = sportscar.fuelneeded(dist);
        System.out.println("To go ", + dist + " miles sportscar needs " + gallons + " gallons of fuel.");
    }
}

但是,运行此代码后,我收到一条错误消息,提示“错误:找不到适合println(String,String)的方法”。为什么会这样?

2 个答案:

答案 0 :(得分:2)

您不能将System.out.println 2 参数一起使用,仅将其传递为 1 字符串。

不在字符串内部(在字符串"To go" ,之后)的逗号告诉编译器将字符串视为2个不同的参数。

更改此行:

System.out.println("To go ", + dist + " miles minivan needs " + gallons + " gallons of fuel.");

对此:

System.out.println("To go " + dist + " miles minivan needs " + gallons + " gallons of fuel.");

答案 1 :(得分:0)

由于字符串外出现逗号(,),因此代码显示错误

System.out.println("To go ", + dist + " miles minivan needs " + gallons + " gallons of fuel.");

您的代码应为

System.out.println("To go ," + dist + " miles minivan needs " + gallons + " gallons of fuel.");