计数器如何工作? / 非常基础 Java

How the counter works? / Very basic Java

我有一个代码来自一本书,里面有一个计数器。我不明白为什么它会这样工作。具体来说,counter是怎么统计"for"循环产生的行数的?我看到有一个带有关系运算符和条件表达式的 "if" 循环,但我仍然不清楚代码 "knows" 如何计算行数。这是一个代码:

*/  
class GalToLitTable {  
public static void main(String args[]) {  
double gallons, liters; 
int counter; 

counter = 0; 
for(gallons = 1; gallons <= 100; gallons++) { 
  liters = gallons * 3.7854; // convert to liters 
  System.out.println(gallons + " gallons is " + 
                     liters + " liters."); 

  counter++; 
  // every 10th line, print a blank line        
  if(counter == 10) { 
    System.out.println(); 
    counter = 0; // reset the line counter 
   } 
  } 
 }   

任何帮助将不胜感激

这里发生了三件事:

  • 你有一个要执行 100 次(从 1-100)的 for 循环
  • 在循环中,您将通过递增运算符 ++ 递增计数器,这与调用 counter = counter + 1;.
  • 基本相同
  • 在循环中(递增后),您将检查当前值以查看是否应执行某些操作(在本例中为重置计数器)。

您可以在下面看到一些带注释的代码,这更好地解释了这一点,但我强烈建议您查看上面提供的链接,以获取有关 for 循环和 [=15 的更多详细信息=]运算符:

// Your counter
int counter = 0; 

// The contents of this will execute 100 times
for(gallons = 1; gallons <= 100; gallons++) { 

    // Omitted for brevity

    // This increases your counter by 1
    counter++; 

    // Since your counter is declared outside of the loop, it is accessible here
    // so check its value
    if(counter == 10) { 

         // If it is 10, then reset it
         System.out.println(); 
         counter = 0; 
    } 

    // At this point, the loop is over, so go to the next iteration
} 

counter ++; 表示 counter = counter + 1; 这行代码在 foor 循环的每次迭代中将计数器递增 1。 If 子句在计数器达到 10 时将计数器重置为零,如您在 counter = 0; 中所见。所以在 10 次迭代后计数器达到 10 并且 if 子句的条件为真。