2015-07-13 50 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