-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