仅数组输出最后一个整数

时间:2020-03-11 17:44:11

标签: java arrays while-loop

以前试图弄清楚这一点并且无法弄清楚,它只是打印数组中的最后一个数字。

import java.util.Scanner;
public class proj81 {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int[] arry = new int[11];
        System.out.print("You will be asked to enter a set of 10 integers.\n");
        int i = 1;
        int count = 0;
                while(count<=9) {
                    System.out.print("Please enter an integer: ");
                    arry[i] = reader.nextInt();
                    count++;
                }
                System.out.print(arry[i]);
                }


}

2 个答案:

答案 0 :(得分:3)

当然可以,print语句不在while循环中。试试这个:

while(count <= 9) {
    System.out.print("Please enter an integer: ");
    arry[count] = reader.nextInt();
    count++;
    System.out.print(arry[count]);
}

我已将i替换为count,因为i只是一个常量,所以您不需要填充数组。

答案 1 :(得分:0)

您有两个问题:

  1. 我应该初始化为0,而不是1。
  2. 如果您持有10个数字,则数组的大小应为10。
  3. 如果要在每次添加后输出,请在循环内移动输出。
  4. 如果只想输出整个数组,则将输出更改为: System.out.println(Arrays.toString(arry));
相关问题