gpt4 book ai didi

java - 方法返回 null [简单]

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

对于 Java 入门,我创建了一个 Door 类和一个 DoorTester 类。本质上,我们正在尝试实例变量并创建公共(public)方法。我制作了门类,如下所示,但我的 DoorTester 在查找 .getState 时返回“null”

门.java

public class Door {
// Create instance variables of type String
private String name;
private String state;

// Declare method 'open' and 'close'
public void open() {
state = "open";
}
public void close() {
state = "closed";
}

// Add a constructor for the Door class
public Door(String name, String state) {
}

// Create an accessor of 'state'
public String getState() {
return name;
}

// Set the state
public void setState(String newState) {
state = newState;
}

}

DoorTester.java

public class DoorTester {
public static void main(String[] args) {
Door frontDoor = new Door("Front", "open");
System.out.println("The front door is " + frontDoor.getState());
System.out.println("Expected: open");
Door backDoor = new Door("Back", "closed");
System.out.println("Expected: closed");
// Use the mutator to change the state variable
backDoor.setState("open");
System.out.println("The back door is " + backDoor.getState());
System.out.println("Expected: open");
// Add code to test the setName mutator here
}

}

最佳答案

您必须修改 Door 类的构造函数,例如

public Door(String name, String state) {
this.name=name;
this.state=state;
}

实际上namestate没有被初始化。另请参阅此 What is the meaning of "this" in Java?

<小时/>

修改后的代码片段:

public class Door {
// Create instance variables of type String
private String name;
private String state;

// Declare method 'open' and 'close'
public void open() {
state = "open";
}
public void close() {
state = "closed";
}

// Add a constructor for the Door class
public Door(String name, String state) {
this.name=name;
this.state=state;
}

// Create an accessor of 'state'
public String getState() {
return state; //<<<<<<<----------also make an Edit here
}

// Set the state
public void setState(String newState) {
state = newState;
}
}

关于java - 方法返回 null [简单],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26052179/

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