gpt4 book ai didi

java - 这是如何编写此 = new constructor name 的正确方法?
转载 作者:行者123 更新时间:2023-11-29 05:28:17 29 4
gpt4 key购买 nike

谁能帮我解决这段代码的最后一部分的编译错误它的说法创建构造函数请帮助

public class Officer {

public static void main(String args[]) {

Scanner input = new Scanner(System.in);

System.out.print("Enter the name of the Soldier: ");

String name = input.nextLine();

System.out.print("Enter the sex of the Soldier: ");

String sex = input.nextLine();

System.out.print("Enter the Age of the Soldier: ");

String age = input.nextLine();

Soldier soldier = new Soldier(name, sex, age);
}
}

package officer; 

public class Soldier {

private String soldierName;
private int soldierAge;
private char soldierSex;

public void Soldier( String name, char sex, int age) {
soldierName = name;
soldierSex = sex;
soldierAge = age;
}

public String getSoldierName() {
return soldierName;
}
public char getSoldierSex() {
return soldierSex;
}
public int getSoldierAge() {
return soldierAge;
}
}

最佳答案

Soldier需要定义一个匹配的构造函数

public Soldier (String name, String sex, String age) {
// do stuff
}

这是调用new Soldier(name, sex, age)

时执行的方法

关于java - 这是如何编写此 <class name> <object name > = new constructor name 的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21968968/

29 4 0