Java program for taking user input using Scanner and Store into Variables and Array
When you start learning Java programming, many times you need to get input from user and store into some variables or array.
We can use Scanner class that presents in "java.util.Scanner" for taking user inputs.
We can not store String value to int or any other data type value to other one, so Scanner class have particular methods for getting specific user input.
Scanner class have many methods for taking user input i.e,
- For taking int value = nextInt()
- For taking String value = next()
- For taking Float value = nextFloat()
You can see all methods on Java doc :
Program 1 : Getting User Input using Scanner Class
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
// Creating Scanner class object and initialize it
Scanner sc = new Scanner(System.in);
System.out.println("Enter String :");
// Getting String user input and store into s variable
String s = sc.next();
// Print user input
System.out.println("String value is : "+ s);
}
}
Output :
Enter String :
Java Programming Scanner Class Demo
String value is : Java Programming Scanner Class Demo
Program 2 : Storing Array values from User input using Scanner Class
import java.util.Scanner;
public class FindTheMedian {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Array Length : ");
int length = sc.nextInt();
// Creating and Initializing Array with User input length
int[] array = new int[length];
// Traverse through 0 to length and enter user input into Array
System.out.println("Enter Elements : ");
for (int i = 0; i < length; i++) {
array[i] = sc.nextInt();
}
// Print Array Elements one by one
System.out.println("Printing Array Elements : ");
for (int i = 0; i < length; i++) {
System.out.print(array[i] +" ");
}
}
}
Output :
Enter Array Length :
5
Enter Elements :
10 5 15 20 2
Printing Array Elements :
10 5 15 20 2
We can also add user input data into Array list same as above we put in array.
RECOMMENDED ARTICLES :
Comments
Post a Comment