简体   繁体   English

打印所有输入

[英]Printing Out All Inputs

I just want this program to print all the inputs in the second to the last line of the output. 我只希望该程序在输出的第二行到最后一行打印所有输入。 Please help me how to fix it. 请帮我解决问题。

 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);
    }
}

You are only printing out the array at element i one time because it is not in a loop. 您一次只在元素i上打印数组,因为它不在循环中。

If you want to print out every element in the array you can use an enhanced for loop like this. 如果要打印出数组中的每个元素,可以使用增强的for循环,如下所示。

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

This should loop through each element in the array giving the value to x and print it out. 这应该遍历数组中的每个元素,将值赋给x并打印出来。

OR 要么

You can make a loop that only prints out the digits that have been entered in the array like this. 您可以进行这样的循环,仅打印出在数组中输入的数字,如下所示。

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

Hopefully this is what you want. 希望这是您想要的。 Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM