Java User Input
The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:
package afterfeb13;
import java.util.Scanner;
public class scanner {
public static void main(String[] args) {
int total = 0;
int count = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter name");
String name = sc.nextLine();
System.out.println("Welcome to java: " + name);
int[] mark = new int[5];
for (int i = 0; i < mark.length; i++) {
mark[i] = sc.nextInt();
System.out.println("Enter 10th marks = " + mark[i]);
total = total + mark[i];
}
System.out.println("Total of 10th = " + total);
int[] marks = new int[6];
for (int j = 0; j < marks.length; j++) {
marks[j] = sc.nextInt();
System.out.println("Enter 12th marks = " + marks[j]);
count = count + marks[j];
}
System.out.println("Total of 12th = " + count);
}
}
Output:
Enter name
neelakandan
Welcome to java: neelakandan
98
Enter 10th marks = 98
87
Enter 10th marks = 87
76
Enter 10th marks = 76
56
Enter 10th marks = 56
87
Enter 10th marks = 87
Total of 10th = 404
97
Enter 12th marks = 97
89
Enter 12th marks = 89
97
Enter 12th marks = 97
89
Enter 12th marks = 89
98
Enter 12th marks = 98
67
Enter 12th marks = 67
Total of 12th = 537
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:
**nextBoolean()-Used for reading Boolean value
nextByte()-Used for reading Byte value
nextDouble()-Used for reading Double value
nextFloat()-Used for reading Float value
nextInt()-Used for reading Int value
nextLine()-Used for reading Line value
nextLong()-Used for reading Long value
nextShort()-Used for reading Short value**
Top comments (0)