2016-04-20 74 views
-2

我需要一點幫助理解構造函數。它不是完整的代碼,我只需要幫助理解一個部分。我的代碼如下:Java構造函數語法問題

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函數。任何語法幫助將是真棒!

謝謝!

+1

爲什麼你不想使用set函數嗎?這似乎是使用一個完美的場景。 –

+0

它適用於我正在參加的在線課程及其定義的不能改變的學校課程。爲了學習的目的,我想,我希望我能以自己的方式去做。 – ImSobesBoosted

+0

如果您提供的學校課程是整個學校課程,並且您無法更改它,那麼真的沒有辦法在對象中設置busNumber。有更多的類定義嗎? –

回答

1

有了你張貼在這裏的代碼,因爲busNumber被聲明爲private ... 您需要(是一個很好的做法)來定義一個二傳手在類學校成員總線,可以是不可能的使用公共成員,但因爲你需要更改busNumber公衆的訪問是不是一個很好的OOP設計...

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

,並從主Java調用它

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

注意你需要確認你所讀的是一個數字,因爲下一行是返回一個字符串...

+1

嗯,op說'我也不想使用set函數。 – user3437460

+0

不能使用set函數,但是謝謝! – ImSobesBoosted

+0

如果你不使用setter你需要改變busnumber的訪問,但我不推薦這個 –

1

所以如果你需要不使用一個二傳手,你可能需要把它的構造。

所以你的構造將

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

然後後面的代碼中,你可以調用,如果需要獲得s1.getBusNumber()