Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
计数器是如何工作的?/非常基本的Java_Java_Counter - Fatal编程技术网

计数器是如何工作的?/非常基本的Java

计数器是如何工作的?/非常基本的Java,java,counter,Java,Counter,我有一本书的密码,里面有计数器。我不明白为什么它是这样工作的。具体来说,计数器如何对“for”循环生成的行进行计数?我看到有一个带有关系运算符和条件表达式的“if”循环,但我仍然不清楚代码如何“知道”计算行数。下面是一个代码: */ class GalToLitTable { public static void main(String args[]) { double gallons, liters; int counter; counter = 0; for(gallon

我有一本书的密码,里面有计数器。我不明白为什么它是这样工作的。具体来说,计数器如何对“for”循环生成的行进行计数?我看到有一个带有关系运算符和条件表达式的“if”循环,但我仍然不清楚代码如何“知道”计算行数。下面是一个代码:

*/  
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 
   } 
  } 
 }   
*/
类GalToLitTable{
公共静态void main(字符串args[]){
双加仑,升;
整数计数器;
计数器=0;

对于(加仑=1;加仑这里有三件事:

  • 您有一个
    for
    循环,将执行100次(从1到100)
  • 在循环中,您将通过递增运算符
    ++
    递增计数器,这与调用
    计数器=计数器+1;
    基本相同
  • 在循环中(增量之后),您将检查当前值,以查看是否应该执行某些操作(在本例中,重置计数器)
您可以在下面看到一些带注释的代码,这可以更好地解释这一点,但我强烈建议您查看上面提供的链接,了解有关
for
循环和
increment
运算符的更多详细信息:

// 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
} 
//您的计数器
int计数器=0;
//此文件的内容将执行100次

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

这只是一个基本答案: