Java For循环不能增量

时间:2015-07-13 03:26:51

标签: java for-loop while-loop increment

我一直在尝试在类InputArray的第一个For循环中使System.out.println说"输入第一个整​​数","输入第二个ineger&#34 ;,"输入第3个整数"等,直到第5个。

import java.util.Scanner ;
class InputArray
{
  public static void main ( String[] args )
 {
   int[] array = new int[5];     //5 elements 4 indexs
   int   data;
   Scanner scan = new Scanner( System.in );
   // input the data
  for (int index=0; index <array.length; index++)
    {
       //I tired x=0 here with x++ after this line to increase x until 5.
     System.out.println( "enter the integer: " );
       //I also tried changing the previous line to: 
   //System.out.println( "Enter the " + (count+1) + "th integer" );
     data = scan.nextInt();
     array[ index ] = data ;

     }
  for (int index=0; index <array.length; index++)   
    {
     System.out.println("array ["+index+"] = "+array[index]);
    }
  }
}

但这只会导致&#34;输入第1个整数&#34;对于所有5个输出。类InputArray中的第二个For循环有效,但我注意到它,因为变量索引在标题中递增。这个while循环在另一个程序中没有出现这个问题。

import java.util.Scanner;
public class AddUpNumbers1
{
  public static void main (String[] args ) 
 {
  Scanner scan = new Scanner( System.in );
  int value;             // data entered by the user
  int sum = 0;           // initialize the sum
  int count = 0;         // number of integers read in

  System.out.print( "Enter first integer (enter 0 to quit): " );
  value = scan.nextInt();

  while ( value != 0 )    
 {
  //add value to sum
  sum = sum + value;
  // increment count
  count = count + 1;
  //get the next value from the user
  System.out.println( "Enter the " + (count+1) + "th integer (enter 0 to quit):" );
  value = scan.nextInt();      
 }

System.out.println( "Sum of the integers: " + sum );
 }
}

有解决方法吗? for for循环只增加标题中的变量吗?

1 个答案:

答案 0 :(得分:1)

实际上是一个for循环,例如:

for(<initialization>; <condition>; <afterthought>) {
   <action>
}

将作为以下伪代码建议。

while(condition is satisfied)
  perform action
  afterthought

所以,假设您有以下for循环:

for(int i = 0; i < 100; i++) {
   someFunction();
}

初始化(定义变量索引并将其设置为零)后,将检查条件。如果满意,将使用i = 0调用 someFunction ,然后我将增加。

然而,在while循环中,您可以控制它,您可以在执行该循环操作之前递增,或者在结束时或任何时候递增。我个人会建议在处理类似的枚举器时使用while循环。但那只是我和for循环一样好。

有关for循环的更多信息:https://en.wikipedia.org/wiki/For_loop