我的作业要求使用输出显示行号。教授建议我用计数器来做,因为看到Java没有一种简单的方法来打印出当前的行号,我只是按照建议创建了一个计数器。以下代码如下:
//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处启动行计数器,如下所示:
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?
如果需要,请要求澄清!! 谢谢。
答案 0 :(得分:2)
您的打印件位于for循环之外。当计数器为&#34; 6&#34;时,你的for循环结束。当它退出for循环时。这个变量不会改变,因此当前值是&#34; 6&#34;这就是为什么它总是打印&#34; 6&#34;在你的代码下面。如果要打印每条指令的行号,可以执行以下操作:
count = 0;
System.out.println(++count + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
&#34; ++ count&#34;,你在写一行时增加变量,在第一种情况下它应该打印1然后2等等。希望这有助于:)
不需要循环,因为您只对每行计数一次。如果你将这些行放在一个从0到5的循环中,你将每行计数5次。因为您只需要计算每一行一次,您不需要循环,只需要我之前提到的简单增量。希望这清除了为什么不需要循环
答案 1 :(得分:1)
我假设你有一个定义计数的行:
int count;
因此,在for循环之后,你将计数增加到6,然后开始打印,并在for循环的最后一个递增值处留下计数。
因此,删除for循环并只为每行输出预先增加count变量。
int count = 0;
//Display information
System.out.println( (++count) + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
...
答案 2 :(得分: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