我通过为自己做一些基本的练习来练习我的Java技能,并且我试图制作一个简单的基于文本的简单比赛游戏,我想你可以说。唯一的逻辑是,无论哪辆车都更强大,我试图在这里学习的主要观点是OOP。我有4个其他类(Supra,RX7,MX5和S2000)并调用它们。在我的方法' race'它完成了它背后的所有逻辑,我将用户选择的汽车设置为名为' userCar'的变量。我试图在userCar上调用我的getHorsepower()访问器,这样我就能算出谁会赢。我的意图是,如果' userCar'是' supra',然后' userCar.getHorsepower()'将与' supra.getHorsepower()'相同。但是,我收到一条错误消息,说它在if语句中无法解析方法getHorsepower()。我相信它是因为我试图通过变速器调用我的访问器,如果是这样,我该怎么做才能解决这个问题?或者它可能是一个不同的问题。
谢谢你, 纳什
确切错误: 错误:(100,20)java:找不到符号 符号:方法getHorsepower() location:java.lang.String类型的变量userCar
import java.util.Scanner;
public class Cars{
private static Scanner in = new Scanner(System.in);
private int horsepower;
private int year;
private String coo;
public static void main(String args[])
{
Supra supra = new Supra();
RX7 rx7 = new RX7();
MX5 mx5 = new MX5();
S2000 s2000 = new S2000();
supra.specs();
rx7.specs();
mx5.specs();
s2000.specs();
System.out.println("Supra: " + supra.getHorsepower() + "HP");
System.out.println("RX7: " + rx7.getHorsepower() + "HP");
System.out.println("S2000: " + s2000.getHorsepower() + "HP");
System.out.println("MX5 (Miata): " + mx5.getHorsepower() + "HP");
race();
}
public void setHorsepower(int h)
{
this.horsepower = h;
}
public int getHorsepower()
{
return horsepower;
}
public static void race()
{
Supra supra = new Supra();
RX7 rx7 = new RX7();
MX5 mx5 = new MX5();
S2000 s2000 = new S2000();
supra.specs();
rx7.specs();
mx5.specs();
s2000.specs();
String userCar = "";
String compCar = "";
System.out.println("Choose a car to race");
System.out.println("1) Supra | 2) RX7 | 3) S2000 | 4) MX5 (Miata)");
int userChoice = in.nextInt();
System.out.println("Choose a car to race against");
int compChoice = in.nextInt();
if(userChoice == 1)
userCar = "supra";
else if(userChoice == 2)
userCar = "rx7";
else if(userChoice == 3)
userCar = "s2000";
else if(userChoice == 4)
userCar = "mx5";
if(compChoice == 1)
compCar = "supra";
else if(compChoice == 2)
compCar = "rx7";
else if(compChoice == 3)
compCar = "s2000";
else if(compChoice == 4)
compCar = "mx5";
if (userCar.getHorsepower() > compCar.getHorsepower())
{
System.out.println("You won!");
} else { System.out.println("That's embarrassing."); }
}
}
答案 0 :(得分:2)
您正在尝试在Car
类中调用java.lang.String
类的实例。您的userCar
变量是一个字符串。它应该是Car
或Car
子类。
答案 1 :(得分:2)
无法使用字符串作为变量的名称,句号。
但你可以这样做:
Car userCar = null;
if(userChoice == 1)
userCar = supra;
else if(userChoice == 2)
userCar = rx7;
else if(userChoice == 3)
userCar = s2000;
else if(userChoice == 4)
userCar = mx5;
同样适用于compCar
。