java - 如何仅对字符串值设置异常?
问题描述
我正在接受用户的输入,它应该只是字符串,但代码没有按我预期的那样工作。这是我的代码`
while(true){
try{
System.out.print("Enter test string");
str=sc.nextLine();
break;
}
catch(InputMismatchException e) {
System.out.println("Please enter String value");
continue;
}
}
System.out.println(str);
`
如果我给出的整数值比它应该再次询问但这里它正在打印整数值。也没有特殊字符
解决方案
如果你试图直接解析整数,那么你会得到一个更有意义的异常来捕获。
String str = "";
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter test string");
str = sc.nextLine();
Integer.parseInt(str);
System.out.println("Please enter String value");
} catch (NumberFormatException e) {
// You *didn't* get a number; you actually have a String now.
// You can terminate the loop here.
break;
}
}
System.out.println(str);
推荐阅读
- ios - 如何在 iOS 中检查暗模式?
- java - 如何在没有 numpy 的情况下将 Python 代码转换为 Java
- react-native - 如何在 Linux 上手动启动 React Native 调试器 - Ubuntu
- android - 错误:迁移到 androidx 后找不到符号类 MediaStyle
- flutter - 如何使所有列表视图同时可滚动?
- android - 如何使用 MVVM 架构实现 Firebase Google SignIn?
- swift - 在外面点击时如何关闭我的幻灯片菜单?
- node.js - 如何配置 VSCode 的 Organize Imports 顺序?
- r - 分解没有周期性错误的动物园对象
- amazon-s3 - terraform,s3 存储桶策略