Adding another nextLine() between nextInt() and nextLine() is necessary

Introduction

If we read an Integer first and then read strings, it is necessary to add another nextLine() between the nextInt() and nextLine() methods. Otherwise, there will be an InputMismatchException.

1. Program with Exceptions

Codes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.File;
import java.util.Scanner;

public class Test {
public static void main(String[] args) {
File openFile = new File("F://test.txt");
try {
Scanner in = new Scanner(openFile);
System.out.println(in.nextInt()); // 192
// in.nextLine();
System.out.println(in.nextLine()); // Hello World!
System.out.println(in.nextInt()); // 192
} catch (Exception e) {
e.printStackTrace();
}
}
}

The content of the test.txt file

1
2
3
100
Hello World!
200

Outputs

1
2
3
4
5
6
7
8
9
10
100

java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at test.Test.main(Test.java:36)

Process finished with exit code 0

2. Program without Exceptions

Codes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.io.File;
import java.util.Scanner;

public class Test {
public static void main(String[] args) {
File openFile = new File("F://test.txt");
try {
Scanner in = new Scanner(openFile);
System.out.println(in.nextInt()); // 192
in.nextLine(); // Advances this scanner past the current line and returns the input that was skipped.
System.out.println(in.nextLine()); // Hello World!
System.out.println(in.nextInt()); // 192
} catch (Exception e) {
e.printStackTrace();
}
}
}

The content of the test.txt file

1
2
3
100
Hello World!
200

Outputs

1
2
3
4
5
100
Hello World!
200

Process finished with exit code 0

Word count: 222

References

1.Oracle. (2020). Class Scanner (Java Platform SE 7).
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html


This is the ending, thanks for reading.

Exclusive for Local Squires and Tyrants