Is calling Scanner methods without using the read content bad?
I recently ran into some trouble with Java's Scanner. When calling methods such as nextInt()
, it doesn't consume the newline
after pressing Enter. My solution is:
package scannerfix;
import java.util.Scanner;
public class scannerFix {
static Scanner input = new Scanner(System.in);
public static int takeInt() {
int retVal = input.nextInt();
input.nextLine();
return retVal;
}
public static void main(String[] args) {
int num = scannerFix.takeInt();
String word = input.nextLine();
System.out.println("n" + num + "t" + word);
}
}
It works, but here's my question : Is this in any way bad?
"Enter" is not consumed because it equals "n" (in Windows / Linux etc) which is a standard delimiter. You already skip to the next line with input.nextLine();
So your solution is fine!
For more info on how delimiters work regarding the Scanner
class see:
How do I use a delimiter in Java Scanner?
One issue is that it can hide some errors in the input. If you expect there to be an integer on one line, and another on the next, but instead the first line contains "2 a" then you will read it as a 2. For some cases, you might want to reject this input instead and display an error.
链接地址: http://www.djcxy.com/p/78358.html上一篇: Java分隔符问题
下一篇: 调用扫描仪方法而不使用读取内容不好?