2015-07-13 52 views
-2

我一直在尝试使System.out.println在类InputArray的第一个For循环中说“输入第一个整​​数”,“输入第二个整数”,“输入第三个整数“等到第五个。Java For Loop无法递增

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]); 
    } 
    } 
} 

但是,这只会导致所有5个输出的“输入第1个整数”。类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循环只能在其头文件中增加变量吗?

+0

你想在哪里'for'循环如果不能增加在头? –

+0

这是因为你不**在循环内的任何地方递增'count'。 – Codebender

回答

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,然后我会增加。

但是,在一个while循环中,您可以控制此操作,您可以在执行该循环操作或增量操作之前递增或在任何需要的时间递增。我个人会建议使用while循环来处理这样的枚举器。但那只是我和循环都一样好。在for循环

更多信息:https://en.wikipedia.org/wiki/For_loop