-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathScannerValidateInput.java
More file actions
36 lines (33 loc) · 958 Bytes
/
Copy pathScannerValidateInput.java
File metadata and controls
36 lines (33 loc) · 958 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.Scanner;
public class ScannerValidateInput{
public static void main(String[] args){
Scanner inputScanner = new Scanner(System.in);
int lineNum = 0;
// scan this input on a line-by-line basis.
while(inputScanner.hasNextLine()){
// obtain next line
String lineStr = inputScanner.nextLine();
System.out.printf("%d: %s%n", ++lineNum, lineStr);
// parse this line's content in detail with associated Scanner instance.
Scanner scanner = new Scanner(lineStr);
try{
if(scanner.hasNext()){
System.out.printf("Name: %s%n", scanner.next());
}else{
System.out.printf("%d: name field missing%n", lineNum);
continue;
}
if(scanner.hasNextInt()){
System.out.printf("Age: %d%n", scanner.nextInt());
}else{
System.out.printf("%d: age field missing%n", lineNum);
continue;
}
}finally{
System.out.println();
scanner.close();
}
}
inputScanner.close();
}
}