可以判断Scanner(System.in).nextLine()从Console获取的值是否为空或为空格的方法,并抛出异常
代码如下:
System.out.println("输入:");
String s = new Scanner(System.in).nextLine();
if(s.isEmpty()) {
System.out.println("不能输入空");
throw new IllegalArgumentException("不能输入空");
}
if(s.trim().isEmpty()) {
System.out.println("不能输入空格");
throw new IllegalArgumentException("不能输入空格");
}
异常如下: