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!!
But we can take array input by using the method of the Scanner class. To take input of an array, we must ask the user about the length of the array. After that, we use a Java for loop to take the input from the user and the same for loop is also used for retrieving the elements from the array.
To read data from user create a scanner class. Read the size of the array to be created from the user using nextInt() method. Create an array with the specified size. In the loop read the values from the user and store in the array created above.
Java provides three classes to take user input: BufferedReader, Scanner, and Console.
Using Scanner Class This is probably the most preferred method to take input. The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however, it is also can be used to read input from the user in the command line.
Here's a simple code that reads strings from stdin
, adds them into List<String>
, and then uses toArray
to convert it to String[]
(if you really need to work with arrays).
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
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] + " ");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With