Exception when using Java Scanner to read from stdin sequentially
I am learning how to use Scanner in Java, I want to read an integer and a string from stdin, 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 functions readInt
and readString
work well, 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 someone explain where I went wrong?
source to share
Delete call
in.close();
when you close in
you are also close
System.in
global (and it doesn't reopen).
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();
}
Alternatively, you might consider passing to a Scanner
method (s).
public static int readInt(Scanner in) {
System.out.println("Please type in an integer");
return in.nextInt();
}
public static String readString(Scanner in) {
System.out.println("Please type in a string");
return in.nextLine();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Integer you type is: " + readInt(in));
System.out.println("String you type is: " + readString(in));
}
source to share
You can also use the below code
import java.util.Scanner;
public class TryScanner {
Scanner in = new Scanner(System.in);
public void readInt() {
System.out.println("Please type in an integer");
int length = in.nextInt();
System.out.println("Integer you type is: " + length);
}
public void readString() {
System.out.println("Please type in a string");
String s = in.nextLine();
System.out.println("String you type is: " + s);
}
public static void main(String[] args) {
TryScanner instance = new TryScanner();
instance.readInt();
instance.readString();
instance.in.close();
}
}
source to share