0

Using scanner class how to declare an array from getting user input. As well as getting capacity of array from input

25th Dec 2016, 6:23 PM
vaibhav deshmukh
4 Réponses
+ 5
Scanner scan = new Scanner(System.in); int z = scan.nextInt(); int arr[z];
25th Dec 2016, 6:38 PM
Wen Qin
Wen Qin - avatar
+ 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.
26th Dec 2016, 12:56 AM
Ousmane Diaw
+ 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
6th Jan 2017, 4:49 PM
abhishek maurya
abhishek maurya - avatar
+ 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( ); }
25th Dec 2016, 8:52 PM
98LM
98LM - avatar