java - 如果输入不是 bigDecimal,如何抛出异常并再次扫描?
问题描述
我想扫描 bigDecimal 但如果扫描的输入不是 bigdecimal 它应该抛出一个自定义异常并再次扫描它?
我正在尝试以下代码,但无法得出结论。
代码:
import java.util.*;
import java.io.*;
class WrongInputException extends Exception{
WrongInputException(String s){
super(s);
}
}
public class Main
{
public static void main(String[] args) throws WrongInputException
{
try
{
int number;
Scanner sc = new Scanner(System.in);
while (!sc.hasNextBigDecimal())
{
throw new WrongInputException("Wrong data type of input.....");
}
number = sc.nextInt();
System.out.println(number);
} catch(NumberFormatException e) {
System.out.println(e.getMessage());
}
}
}
解决方案
问题是你没有处理你抛出的异常
您应该添加一个 try catch 块以在 thw 内处理它,同时还添加 asc.next();
以避免无限循环
while (!sc.hasNextBigDecimal())
{
try {
throw new WrongInputException("Wrong data type of input.....");
}catch (WrongInputException e) {
e.printStackTrace();
}finally {
sc.next();
}
}
请注意,您的 try catch 没有任何意义,因为您有异常要抛出
推荐阅读
- typo3 - 如何为登录的前端用户临时禁用语音 url?
- python - 当 url 不变时抓取多个页面
- mysql - 无法在 Azure Mysql DB 中创建触发器
- java - 如何计算万有引力?
- mysql - MySQL 来自具有不同列数的不同表的值总和
- node.js - child_process.spawn 在 stdout.read 上返回 null
- node.js - 我正在尝试使用 Angular 将我的后端付款连接到我的前端卡费用。我怎样才能做到这一点?
- terraform - 从 terraform 资源创建记录列表
- r - 编辑数据表中单元格的 RGB 颜色 (R)
- php - 将日期字符串从请求转换为 MySQL 兼容的日期格式