how to take user input in Array using java?

前端 未结 8 1706
你的背包
你的背包 2020-12-03 12:35

how to take user input in Array using Java? i.e we are not initializing it by ourself in our program but the user is going to give its value.. please guide!!

8条回答
  •  长情又很酷
    2020-12-03 13:13

    package userinput;
    
    import java.util.Scanner;
    
    public class USERINPUT {
    
        public static void main(String[] args) {
    
            Scanner input = new Scanner(System.in);
    
            //allow user  input;
            System.out.println("How many numbers do you want to enter?");
            int num = input.nextInt();
    
            int array[] = new int[num];
    
            System.out.println("Enter the " + num + " numbers now.");
    
            for (int i = 0 ; i < array.length; i++ ) {
               array[i] = input.nextInt();
            }
    
            //you notice that now the elements have been stored in the array .. array[]
    
            System.out.println("These are the numbers you have entered.");
            printArray(array);
    
            input.close();
    
        }
    
        //this method prints the elements in an array......
        //if this case is true, then that's enough to prove to you that the user input has  //been stored in an array!!!!!!!
        public static void printArray(int arr[]){
    
            int n = arr.length;
    
            for (int i = 0; i < n; i++) {
                System.out.print(arr[i] + " ");
            }
        }
    
    }
    

提交回复
热议问题