Can Scanner.next() return null or empty string?

佐手、 提交于 2021-01-28 10:51:53

问题


I'm learning Java coming from other programming languages (Js, C and others..)

I'm wondering if under any circumstances the Scanner.next() method could return (without throwing) an invalid string or less than one character (ie. null or empty string ""). I'm used to double-check user input for any possible unexpected/invalid value, but I wanted to know if testing for null and myString.length() < 1 is always unnecessary or could be useful/needed.

I'm asking in particular when reading from the commandline and System.in, not from other Streams of Files. Can I safely get the first character with myString.charAt(0) from the returned value when reading normally from the terminal input (ie. no pipes and no files, straight from terminal and keyboard)?

I searched the Java SE 9 API Docs and couldn't find mentions about possibly unexpected return values. In case anything goes wrong with input it should just throw an Exception, right?

Example (part of main method without imports):

Scanner keyboard = new Scanner(System.in);

System.out.print("Enter a selection (from A to E): ");
String res = keyboard.next();

if (res == null || res.length() < 1) {
    // Unnecessary if?
}

回答1:


Scanner#next can never return null and if the user enters an empty string or a string containing whitespaces only then the method will block and wait for input to scan.

Therefore the if condition is redundant and is not needed at all.




回答2:


Scanner.next can never return null by looking at its source code. From Scanner.next code

while(true){ 
...
if (token != null) {
      matchValid = true;
      skipped = false;
      return token;
 }
 ...
}

It can throw NoSuchElementException if no more tokens are available or IllegalStateException if the scanner is closed according to the docs. So your checks are redundant.



来源:https://stackoverflow.com/questions/47971568/can-scanner-next-return-null-or-empty-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!