假设我想向 Scanner 添加一个方法,nextPositiveInt()该方法类似于,nextInt()除了当检测到负整数时,InputNegativeException会抛出一个自定义。
当有解决方案利用 时,我为什么要这样做hasNextInt()?虽然不那么简洁,但考虑到例外的目的,它似乎更加整洁和合乎逻辑。例如:
扩展扫描仪方法:
Scanner cli = new Scanner(System.in);
boolean inputValid = false;
do
{
System.out.println("Enter your age:");
try
{
int age = cli.nextPositiveInt();
}
catch(InputNegativeException e)
{
System.out.println("You cannot specify a negative age.");
inputValid = false;
}
catch(InputMismatchException e)
{
System.out.println("Your input must be numeric.");
inputValid = false;
}
} while(!inputValid);
hasNext()方法:
Scanner cli = new Scanner(System.in);
do
{
System.out.println("Please enter a positive number!");
while(!sc.hasNextInt())
{
System.out.println("That's not a number!");
sc.next(); // this is important!
}
int number = sc.nextInt();
} while(number <= 0);
因此,假设您还没有回复告诉我为什么这是一个非常糟糕的主意(如果是,请这样做;我想可能有人反对在 Scanner 中进行验证)我对如何去做感到困惑这。我想我需要通过一些小的改动来复制nextInt()in的主体?nextPositiveInt()你甚至可以nextInt()找到任何地方的尸体吗?
很抱歉,我没有代码来显示我所做的任何努力,但我不确定从哪里开始。