2012-09-22 41 views
0

我的任務需要顯示輸出的行號。教授建議我用計數器來做,因爲看到Java沒有簡單的方法來打印出當前的行號,我只是按照建議創建了一個計數器。下面的代碼如下:count incrementer is wrong

//Count Increment 
    for (count = 1; count<= 5; count++) 
    { 

    } 

    //Display information 
    System.out.println(count + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber); 
    System.out.println(count + "." + " " + "Total Rooms:"+ " " + numofRooms); 
    System.out.println(count + "." + " " + "Total Area:"+ " " + totalSqFt + " sq.ft"); 
    System.out.println(count + "." + " " + "The price per Sq. Ft is " + "$" + priceperSqFt); 
    System.out.println(count + "." + " " + "The estimated property value is "+ "$" + estimatedPropertyvalue); 

但是,輸出開始於六行計數器爲證明此:

6. Street: park avenue #44 
6. Total Rooms: 5 
6. Total Area: 2500.0 sq.ft 
6. The price per Sq. Ft is $120.4 
6. The estimated property value is $301000.0 

去掉括號沒有幫助的。我怎樣才能得到行數正確的狀態1,2,3,4,5?

如有需要,請諮詢澄清!謝謝。

+1

嗯,也許你應該從1開始,增量計數器*後*每一行打印? (這個帖子是個玩笑嗎?) –

+1

@HotLicks:你評論中的「笑話」部分對SO相當陌生的人不太歡迎。也許你可以更有禮貌一點? –

+0

Java是一種*程序*語言,也就是說執行語句並且按順序*更改值。所以當你爲(count ...){...}'執行時,它會在它之後執行(除非有其他的控制流程來改變序列,所以當你到達那個關閉的時候)已經增加到了6. –

回答

2

您的打印件位於for循環之外。當for循環退出for循環時,for循環結束。這個變量不會改變,因此當前值是「6」,這就是爲什麼它總是在代碼上打印下面的「6」。如果你想打印每個指令的行號,你可以做這樣的事情:

 count = 0; 
     System.out.println(++count + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber); 

「++數」,你增加的變量,你寫一行的那一刻,在第一種情況下它應該打印1然後2等希望這有助於:)

該循環不是必需的,因爲你只計算每行一次。如果你把這些行放在一個從0到5的循環中,你將每行計數5次。既然你只需要對每一行進行一次計數,你就不需要這個循環,而只需要前面提到的簡單增量。希望這清除了,爲什麼不要求循環

+0

+1。您可能想要進行編輯以提及不需要循環,並解釋爲什麼不行,僅供稍後在搜索中發現此問題的人員今後使用。 –

+0

你會用前增量來混淆他太多。最好從1開始計數,並在每個println之間添加一個單獨的增量行。 –

+0

@ rdk1992非常有幫助。我不知道你可以像++那樣增加計數,以便在打印行時增加。非常感謝! – Brian

1

我假設你有上面這一行定義計數的地方:

int count; 

所以for循環,你增加的計數後,6,然後開始在for循環的最後增加的值處留下計數值進行打印。

所以,刪除for循環,只是預先增加每行輸出的計數變量。

int count = 0; 

//Display information 
System.out.println((++count) + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber); 

... 
1
class Print{ 

    static int lineno = 0; 

    private int static getLineNo(){ 
     lineno = lineno + 1; 
     return lineno; 
    } 
} 


//Display information 
System.out.println(Print.getLineNo() + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber); 
System.out.println(Print.getLineNo() + "." + " " + "Total Rooms:"+ " " + numofRooms); 
System.out.println(Print.getLineNo() + "." + " " + "Total Area:"+ " " + totalSqFt + " sq.ft"); 
System.out.println(Print.getLineNo() + "." + " " + "The price per Sq. Ft is " + "$" + priceperSqFt); 
System.out.println(Print.getLineNo() + "." + " " + "The estimated property value is "+ "$" + estimatedPropertyv 
+0

或者你可以寫自己的'printlnWithLineNumber'例程。 –

+1

很高興看到另一種解決方案。 – Brian