0

My assignment calls for the line number to be display with the output. The professor suggested I do it with a counter and as seeing Java doesn't have an easy way to print out the current line number, I just created a counter as suggested. The below code is as follows:

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

However, the output starts the line counter at six as demonstrated here:

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

Removing the brackets doesn't help either. How can I get the line count to correctly state 1,2,3,4,5?

Please ask for clarification if needed!! Thanks.

4

3 回答 3

2

您的打印在 for 循环之外。当计数器为“6”时,您的 for 循环结束,即退出 for 循环。这个变量不会改变,所以当前值为“6”,这就是为什么它总是在你的代码下面打印“6”。如果要打印每条指令的行号,可以执行以下操作:

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

“++count”,你在写一行的时候增加变量,在第一种情况下它应该打印 1 然后 2 等等。希望这有帮助:)

该循环不是必需的,因为您只计算每行一次。如果您将这些行放在一个从 0 到 5 的循环中,您将计算每行 5 次。由于您只需要计算每一行一次,因此您不需要循环,而只需我之前提到的简单增量。希望这可以清除为什么不需要循环

于 2012-09-22T02:06:31.607 回答
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
于 2012-09-22T02:11:30.300 回答
1

我假设您在此之上的某个地方有一个定义计数的行:

int count;

因此,在 for 循环之后,您将 count 增加到 6,然后开始打印,count 位于 for 循环中最后一个递增的值。

因此,删除 for 循环并为每行输出预先增加 count 变量。

int count = 0;

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

...
于 2012-09-22T02:09:09.413 回答