gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:44:00 25 4
gpt4 key购买 nike

我是 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) 的合适方法”。为什么会发生这种情况?

最佳答案

您不能将 System.out.println2 参数一起使用,只能传递 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.");

关于java - 在字符串中打印整数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53979509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com