2013-09-26 58 views
1
public class BottledWaterTester { 
public static void main (String args[]) 
{ 
    BottledWaterCalculator tester = new BottledWaterCalculator("USA", 350000000, 190.0, 8.5, 12.0); 


    System.out.println("The country is " + tester.getCountryName()); 
    System.out.println("The population is " + tester.getPopulation()); 
    System.out.println("The number of times the bottles circle the Equator is " + tester.getNumberCircled()); 
    System.out.println("The average length of a bottle is " + tester.getLength()); 
    System.out.println("The average volume of a bottle is " + tester.getVolume()); 
} 

}參數將不會傳遞到目標

所以我上面這段代碼。但是,當我運行它,我得到這個輸出:

*運行:

該國爲空

人口爲0

瓶繞赤道的次數爲0.0

瓶子的平均長度爲0.0

瓶子的平均容積爲0.0

BUILD SUCCESSFUL(總時間:0秒)*

原因?我明確地將值傳遞給我的測試器對象。這裏的構造函數定義如下:

public class BottledWaterCalculator { 

//instance vars 
private String countryName; 
private int population; 
private double numberCircled; 
private double avgLength; 
private double avgVolume; 

//constructor 
// note: constructor name must always be same as public class name, or else it's a method 
public BottledWaterCalculator(String country, int pop, double number, double lengthAvg, double volumeAvg) 
{ 
    country = countryName; 
    pop = population; 
    number = numberCircled; 
    lengthAvg = avgLength; 
    volumeAvg = avgVolume; 
} 

我真的很新來編程,所以我不明白髮生了什麼事情。變量

+0

您需要執行'this.countryName = country',因爲作業的左側(LHS)是設置到RHS的等等。也許在你的問題中標記Java – KeepCalmAndCarryOn

+0

THANK YOu。有效。 Java非常細緻。 –

回答

1
public BottledWaterCalculator(String country, int pop, double number, double lengthAvg, double volumeAvg) 
{ 
    countryName = country ; 
    population= pop; 
    numberCircled = number ; 
    avgLength = lengthAvg; 
    avgVolume = volumeAvg ; 
} 

錯誤的順序,你是構造函數的參數分配值,而不是對象一個

0

在你的構造翻轉變量賦值。例如:

countryName = country; 

您當前正在設置要傳入的局部變量值。 (裏面全是空/空/未分配)

0

變化下面的代碼:

public class BottledWaterCalculator { 

//instance vars 
private String countryName; 
private int population; 
private double numberCircled; 
private double avgLength; 
private double avgVolume; 

//constructor 
// note: constructor name must always be same as public class name, or else it's a method 
public BottledWaterCalculator(String country, int pop, double number, double lengthAvg, double volumeAvg) 
{ 
    countryName = country; 
    population = pop; 
    numberCircled = number ; 
    avgLength = lengthAvg ; 
    avgVolume = volumeAvg ; 
} 
0

你需要指定這個關鍵字,而分配給構造函數。

+1

歡迎來到Stack Overflow!就目前而言,這個答案更適合作爲評論。也許你可以通過添加提問者可以用來解決問題的演示代碼來改進它? –