简体   繁体   中英

Input Number to Array java

I'm doing a Java activity that prints the Numbers the user Input, and here's my codes:

System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
for (int x = 1; x<=num1;x++){
    for (int i = 0 ; i<num1;){
        System.out.print("Enter Value #" + x++ +":");
        int ctr1 =Integer.parseInt(in.readLine());
        i++;
    }
}

How can I print all the input numbers? Here's the result of my code:

Enter How Many Inputs: 5
Enter Value #1:22
Enter Value #2:1
Enter Value #3:3
Enter Value #4:5
Enter Value #5:6

How can I print all this numbers as array. 22,1,3,5,6

Create an int[] array of length num. On every iteration take the user input and put it in the array at their specified index and break out of the while loop. and at last print the array elements by iterating over it.

    Scanner scan = new Scanner(System.in);
        System.out.println("enter num of values: ");
        int [] arr = new int[scan.nextInt()];
        for(int i=0;i<arr.length; i++) {
            scan = new Scanner(System.in);
            System.out.println("please enter a value: ");
            while(scan.hasNextInt()){
            int x = scan.nextInt()
                    ;
            arr[i]= x;
            break;
            }

        }
        for(int i:arr){
            System.out.print(i);
        }

OUTPUT: enter num of values: 5 please enter a value: 22 please enter a value: 2 please enter a value: 3 please enter a value: 5 please enter a value: 6 22 2 3 5 6

System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
int arr[] = new int[num1];

for (int i = 0; i<num1; i++)
{
    System.out.print("Enter Value #" + (i + 1) + ":");
    arr[i] =Integer.parseInt(in.readLine());
}

I guess this should do it... NOT TESTED


PRINTING

for(int i = 0; i < arr.length; i++)
    System.out.println(arr[i]);

SORTING

import java.util.Arrays;

Inside the code block

Arrays.sort(arr);

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