我有一个主要类,看起来像这样:
class Main {
public static void main (String[] args) {
Mobil one = new Mobil ("xxxxxx", "yyyyyy", 00000001, true);
Mobil two = new Mobil ("yyyyyy", "xxxxxx", 10245624, false);
one.touchcontrol();
two.touchcontrol();
}
}
我有这个美孚课程:
class Mobil {
String type;
String manufactureat;
int modellnumber;
boolean touchtype;
public Mobil (String manufacturer, String inittype, int number, boolean touch) {
manufacturer = manufactureat;
inittype = type;
number = modellnumber;
touch = touchtype;
}
public void touchcontrol() {
if (touchtype == false)
{
System.out.println("This model, has not got Touchscreen!");
}
else
{
System.out.println("This model, has Touchscreen!");
}
}
但是当我运行程序并调用one.touchcontrol();
和two.touchcontrol();
时,它显示没有模型有触摸屏。我不知道我错过了什么。
答案 0 :(得分:7)
您需要在构造函数中交换变量赋值。
manufactureat = manufacturer;
type = inittype;
modellnumber = number;
touchtype = touch;
在Java(以及几乎所有其他语言)中的变量赋值中,左手将检索右手的值。
答案 1 :(得分:1)
您错误地将值分配给构造函数中的变量...
public Mobil (String manufacturer, String inittype, int number, boolean touch) {
manufacturer = manufactureat; // should be manufactureat = manufacturer;
inittype = type; //same problem
number = modellnumber; // same here
touch = touchtype; // and here
}