-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScanEveryLineExample.java
More file actions
65 lines (55 loc) · 1.4 KB
/
ScanEveryLineExample.java
File metadata and controls
65 lines (55 loc) · 1.4 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package example;
import java.io.PrintStream;
import java.util.Scanner;
/**
* Scan Every Line example.
*
* @author Osmund
* @version 11.2.0
* @since 2.0.0
*/
public class ScanEveryLineExample {
/**
* Example for running a program with scanner against fixed/file/resource input.
*
* @param scanner program {@link java.util.Scanner}
* @param out program {@link java.io.PrintStream}
*/
public static void program(Scanner scanner, PrintStream out) {
String line = firstLine(scanner);
out.print("[" + line + "]");
while (hasNextLine(scanner)) {
line = nextLine(scanner);
out.println();
out.print("[" + line + "]");
}
}
private static String firstLine(Scanner scanner) {
// Check for empty first line.
scanner.useDelimiter("");
if (scanner.hasNext("\\R")) {
scanner.useDelimiter("\\R");
return "";
}
// Check for empty input.
scanner.useDelimiter("\\R");
if (!scanner.hasNext()) {
return "";
}
return scanner.next();
}
private static boolean hasNextLine(Scanner scanner) {
return scanner.hasNext() || scanner.hasNextLine();
}
private static String nextLine(Scanner scanner) {
if (scanner.hasNext()) {
return scanner.next();
}
// Check for trailing form-feed character.
scanner.skip("\f?");
if (scanner.hasNextLine()) {
return scanner.nextLine();
}
return "";
}
}