打印输出所有输入

时间:2015-10-26 05:29:58

标签: java while-loop java.util.scanner

我只想让这个程序打印输出的第二行到最后一行的所有输入。请帮我解决一下。

 public static void main(String[] args) {
        int[] array = new int[10];
        int sum = 0;
        int i = 0;
        Scanner input = new Scanner(System.in);
        while (sum <= 5 && i < array.length) {
            System.out.print("Enter the " + (i + 1) + "th number: ");


            array[i] = input.nextInt();
            sum += array[i];
            i++;

        }
        System.out.print("Your digits are: ");
        System.out.print(array[i] + " ");
        System.out.println("\nsum is " + sum);
    }
}

1 个答案:

答案 0 :(得分:0)

您只在元素i处打印出数组,因为它不在循环中。

如果要打印出数组中的每个元素,可以像这样使用增强的for循环。

for(int x : array){
  System.out.print(x + " ");
}

这应循环遍历数组中的每个元素,将值赋予x并将其打印出来。

OR

你可以创建一个循环,只打印出像这样在数组中输入的数字。

      int x = 0;
      for(; x < i; x++){
        System.out.print(array[x] + " ");
       }

希望这就是你想要的。希望它有所帮助。

相关问题