我需要一些帮助来理解构造函数。它不是完整的代码我只需要帮助理解一个部分。我的代码如下:
School.java
public class School {
private String name;
private int busNumber;
enter code here
public School (String name) {
this.name = name;
}
public String getSchoolName() {
return name;
}
public int getBusNumber() {
return bus Number;
}
Main.Java
System.out.println("Enter school number 1: ");
school1 = keyboard.nextLine();
School s1 = new School(school1);
System.out.println("Enter school number 2: ");
school2 = keyboard.nextLine();
School s2 = new School(school2);
System.out.println("School 1 is " + s1.getName());
System.out.println("School 2 is " + s2.getName());
System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
//现在我要做的是将公交车号码发送到getBusNumber。
//如何发送bus1以便我可以使用s1.getBusNumber();稍后拨打这个号码!我觉得这应该很容易,但我无法掌握它或找到如何在任何地方做到这一点。我也不想使用set函数。任何语法帮助都很棒!!
谢谢!
答案 0 :(得分:1)
使用您在此处发布的代码是不可能的,因为 busNumber 被声明为私有... 您需要(这是一个很好的做法)在类School中为成员总线定义一个setter,您可以使用公共成员但不是一个好的oop设计,因为您需要更改访问权限busNumber公开......
public void setBusNumber(int number) {
this.busNumber = number;
}
并从主java
中调用它System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
s1.setBusNumber(bus1);
请注意您需要验证您所读取的内容是否为数字,因为下一行正在返回字符串......
答案 1 :(得分:1)
因此,如果您不需要使用setter,则可能需要将其放在构造函数中。
所以你的构造函数将是
public School (String name, int busNumber) {
this.name = name;
this.busNumber = busNumber
}
并且您的代码看起来像这样
System.out.println("Enter school number 1: ");
school1 = keyboard.nextLine();
System.out.println("Enter school number 2: ");
school2 = keyboard.nextLine();
System.out.println("School 1 is " + school1);
System.out.println("School 2 is " + school2);
System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
int intBus1 = Integer.parseInt(bus1)
School s1 = new School(school1, intBus1);
然后在您的代码中,您可以根据需要调用get s1.getBusNumber()