I'm learning how to use Scanner in Java, I want to read from stdin an integer and a string, so I write the following code:
import java.util.Scanner;
public class TryScanner {
public void readInt() {
Scanner in = new Scanner(System.in);
System.out.println("Please type in an integer");
int length = in.nextInt();
System.out.println("Integer you type is: " + length);
in.close();
}
public void readString() {
Scanner in = new Scanner(System.in);
System.out.println("Please type in a string");
String s = in.nextLine();
System.out.println("String you type is: " + s);
in.close();
}
public static void main(String[] args) {
TryScanner instance = new TryScanner();
instance.readInt();
// throw exception when called after readInt()
instance.readString();
}
}
My readInt
and readString
function work well separately, however, when I call them sequentially, only the first function works, an exception is thrown for the second:
Please type in an integer
3
Integer you type is: 3
Please type in a string
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1597)
at helloworld.Sort.readString(Sort.java:17)
at helloworld.Sort.main(Sort.java:27)
Can somebody explain where I did wrong?