Scanner.next()是否可以返回null或空字符串? [英] Can Scanner.next() return null or empty string?

查看:65
本文介绍了Scanner.next()是否可以返回null或空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习来自其他编程语言(Js,C和其他语言)的Java

我想知道在任何情况下 Scanner.next()方法是否可以返回(不抛出)无效字符串或少于一个字符(即 null )或空字符串" ).我习惯于仔细检查用户输入的任何可能的意外/无效值,但我想知道是否测试了 null myString.length()<1 总是不必要的,或者可能有用/需要.

我要特别询问的是何时从命令行和 System.in 中读取,而不是从其他文件流中读取.当从终端输入正常读取时(例如,没有管道也没有文件,直接从终端和键盘读取),我可以安全地从返回值中获得 myString.charAt(0)的第一个字符吗?

我搜索了Java SE 9 API文档,但找不到关于可能意外的返回值的提及.如果输入有任何问题,应该抛出一个异常,对吧?

示例(不带导入的主要方法的一部分):

 扫描仪键盘=新的Scanner(System.in);System.out.print(输入选择(从A到E):");字符串res = keyboard.next();if(res == null || res.length()< 1){//不需要吗?} 

解决方案

). 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?
}

解决方案

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.

这篇关于Scanner.next()是否可以返回null或空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆