0

我需要帮助弄清楚如何让用户输入不超过 10 个整数,然后将它们添加到数组中并从数组中打印出来。我下面的代码在运行时向用户询问整数,然后永远运行并且不起作用。我究竟做错了什么?

public static void main(String[] args) {

    Scanner input = new Scanner(System.in); // create a new scanner
    System.out.print("Enter integers between 1 and 100\n ");  
    int[] nextNumber = new int[10];
    int i = 0;
    int number = input.nextInt();

    while (i < nextNumber.length){
        i++;
        nextNumber[i] = number;
        number = input.nextInt();    
    }

    int a = 0;

    while (a  < nextNumber.length){
        a++;
        System.out.println(nextNumber[a]);   
    }
4

4 回答 4

2

在我看来,您增加索引的速度太快了。您应该在循环结束时增加索引变量,而不是开始

我建议您改用 for 循环,因为它们是为此而设计的:

Scanner input = new Scanner(System.in); // create a new scanner
System.out.print("Enter integers between 1 and 100\n ");

int[] nextNumber = new int[10];

for (int i = 0; i < nextNumber.length; i++){
    nextNumber[i] = input.nextInt();
}

for (int a = 0; a  < nextNumber.length; a++){
    System.out.println(nextNumber[1]);
}

另外,虽然我没有在代码中更改它,但您的最后一行似乎应该是:

System.out.println(nextNumber[a]);
于 2013-10-22T03:26:01.400 回答
1

将值分配给数组后增加数组索引

while (i < nextNumber.length) {
    number = input.nextInt();
    nextNumber[i] = number;
    i++;
}

这同样适用于第二个循环

while (a < nextNumber.length) {
    System.out.println(nextNumber[a]);
    a++;
}
于 2013-10-22T03:24:14.193 回答
0

问题 1

改变

int i = 0;
int number = input.nextInt();
while (i < nextNumber.length){
i++;  //here is one problem. you not assigning the value to nextNumber[0].
nextNumber[i] = number;
number = input.nextInt();

}

int i = 0;
while (i < nextNumber.length){
   number = input.nextInt();
   nextNumber[i] = number;
   i++;  
}

问题 2

改变

int a = 0;
while (a  < nextNumber.length){
    a++;  //here is one problem ..You never get  nextNumber[0] value
System.out.println(nextNumber[a]);

}

int a = 0;
while (a  < nextNumber.length){
     System.out.println(nextNumber[a]);
    a++;
}
于 2013-10-22T03:20:53.830 回答
0

您可以按如下方式轻松执行此操作。更好地使用 for 循环,因为您知道最大迭代次数。

Scanner input = new Scanner(System.in); // create a new scanner
System.out.print("Enter integers between 1 and 100\n ");  
int[] nextNumber = new int[10];

int i = 0;
while (i < nextNumber.length)   nextNumber[i++] =  input.nextInt();


int a = 0;
while (a  < nextNumber.length)  System.out.println(nextNumber[a++]);  
于 2013-10-22T03:56:22.363 回答