-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循環只能在其頭文件中增加變量嗎?
你想在哪裏'for'循環如果不能增加在頭? –
這是因爲你不**在循環內的任何地方遞增'count'。 – Codebender