简体   繁体   中英

Java Constructor Syntax Issue

I need a little help understanding constructors. It isnt full code I just need help understanding one part. My code is as follows:

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();

//Now what I want to do is send the bus numbers to getBusNumber.

//How do I send bus1 so I can use s1.getBusNumber(); to call the number later! I feel like this should be so easy but I can't grasp it or find how to do it anywhere. I also do not want to use a set function. Any syntax help would be awesome!!

Thanks!

With the code you posted here is not possible since the busNumber is declared private... You need (is a good practice) to define a setter for the member bus in the class School, you can to use public members but is not a good oop design since you need to change the access of the busNumber to public...

public void setBusNumber(int number) {
    this.busNumber = number;
}

and call it from the main java

System.out.println("Enter the bus number 1: ");
bus1 = keyboard.nextLine();
s1.setBusNumber(bus1);

Be aware you need to validate that what you read is a number because next line is returning strings...

So if you need to not use a setter, you probably need to put it in the constructor.

So your constructor would be

public School (String name, int busNumber) {
    this.name = name;
    this.busNumber = busNumber
}

and your code would look like this

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);

Then later in your code you can call get s1.getBusNumber() if needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM