0
Using scanner class how to declare an array from getting user input. As well as getting capacity of array from input
4 Réponses
+ 5
Scanner scan = new Scanner(System.in);
int z = scan.nextInt();
int arr[z];
+ 2
@98LM shows the almost perfect answer to your question but it's error prone. You wouldnt want to directly take user input and store it into an integer array, how about i enter "bug" or anything thats not integer. Oops "InputMismatchException". Anyway the idea is first use the Scanner "hasNextInt()" method prior to assigning the value to a particular index in the array.
However having said all that, if you're complete sure its just you entering the values then thats fine but when ever you create code , you must always think of the ways it COULD GO WRONG.
+ 2
first you need to import a package java. util.*;
because scanner class belong to this package
then you need to create an object of scanner class
Scanner sc= new Scanner (system. in);
int n=sc.nextInt ();//take the input by user
int [] ar= new int [n];//set the limit of array using n
+ 1
Scanner input = new Scanner(System.in);
int x = input.nextInt( );
int array[ ] = new int [ x ];
for ( int i=0;i<array.length;i++){
array [ i ] = input.nextlnt( );
}