如何从数组中打印出int值?

时间:2014-11-12 17:55:27

标签: java loops for-loop

下面的代码显示了我的进度,但我无法打印输入的数字。我不知道将println("you entered the following numbers")放在循环中的哪个位置,以便在循环停止时显示它。

import java.util.Scanner;

public class aufgabe5 {
    public static void main(String[] args) {

        int x;
        Scanner input = new Scanner(System.in);
        System.out.println("How much numbers do you want to enter?");
        x = input.nextInt();
        int j = 1;
        Scanner scanner = new Scanner(System.in);
        int[] numbers = new int[x];
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Enter the " + j++ + ". number:");
            numbers[i] = scanner.nextInt();

        }
        System.out.println("You entered following numbers");
        System.out.println(x);
    }
}

2 个答案:

答案 0 :(得分:1)

更改x,如

System.out.println(x);

Arrays.toString(int[])喜欢

System.out.println(Arrays.toString(numbers));

修改

要反转打印数组,

String str = Arrays.toString(numbers).replace(", ", " ,");
str = str.substring(1, str.length() - 1);
System.out.println(new StringBuilder(str).reverse().insert(0, "[")
            .append("]"));

答案 1 :(得分:0)

在循环之前初始化String,然后继续向其添加值。 循环结束后,您可以打印整个内容。

String someVar="You entered following numbers: ";
for(int 1=0;i<array.length;i++)
{
    someVar=someVar+numbers[i]+",";
}
System.out.println(someVar);