我是Java新手但越来越沉迷于上瘾。 我创建了这些类:
Car car1 = new Car();
car1.model = "Toyota";
car1.price = 1500;
Car car2 = new Car();
car2.model = "Peugeot";
car2.price = 2600;
我用
计算了最高价格 int maxprice=Math.max(car1.price, car2.price);
哪个是标致。
现在我要打印计算价格的模型:
System.out.println("The most expensive car is "+ ????);
这是问题所在。我无法弄清楚这里发生了什么。我认为这将是.getmodel
或其他什么,但我无法获得任何工作。我提前感谢你的帮助。
感谢。
答案 0 :(得分:0)
不要直接指定汽车的名称和价格。使用此
public void setPrice(int price)
{
this.price = price;
}
public void setName(String name)
{
this.name= name;
}
public void getPrice()
{
return price;
}
public void getName()
{
return name;
}
另外要比较价格使用比较器
答案 1 :(得分:0)
这是我最好的解决方案:
public class Main
{
public static void main()
{
Car car1 = new Car();
car1.setModel ( "Toyota" );
car1.setPrice ( 1500 );
Car car2 = new Car();
car2.setModel ( "Peugeot" );
car2.setPrice ( 2600 );
int biggestPrice = Math.max ( car1.getPrice(), car2.getPrice() )
String model = "";
switch ( biggestPrice ) {
case car1.getprice:
model = car1.getModel();
break;
case car2.getPrice:
model = car2.getModel();
break;
default:
assert false : "Got a number that should not be able to appear";
System.out.println ( "ERROR!" );
return;
}
System.out.println("The most expensive car is " + model);
}
class Car
{
String model;
int price;
public Car () {}
public Car ( String model, int price )
{
this.model = model;
this.price = price;
}
public void getModel ( )
{
return this.model;
}
public void setModel (String model )
{
this.model = model;
}
public void getPrice ( )
{
return this.price;
}
public void setPrice ( int price )
{
this.price = price;
}
}
}
希望这有点帮助:)