简体   繁体   中英

How can I print out the int values from the array?

The code below shows my progress, but I cannot print the numbers that were entered. I don't know where to put println("you entered the following numbers") in the loop so that it'll show up when the loop stops.

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

Change x like

System.out.println(x);

to Arrays.toString(int[]) like

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

Edit

To print the array reversed,

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

Intialize the String before the loop, then keep adding the values to it. After the loop finishes you can print the whole thing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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