如何处理用户将无效类型输入扫描仪?

我一直在为家庭作业创建一个简单的计算器,但我可能使用了比我们所教的技术更先进的技术。

这是我的实现,它使用 try/catch 来处理异常。

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("List of operations: add subtract multiply divide alphabetize");
        System.out.println("Enter an operation:");
        String selection = input.next();
        selection = selection.toLowerCase();

        switch (selection) {
            case "add":
                int sum = 0;
                try {
                   int integerOne = input.nextInt();
                   int integerTwo = input.nextInt();
                   sum = integerOne + integerTwo;
                }
                catch (Exception e) {
                    System.out.println("Invalid input entered. Terminating...");
                    break;
                }
                System.out.println("Answer: " + sum);
                break;

我省略了其余的代码,因为它们非常相似,只是用于不同的操作。

如何在不使用 try/catch 的情况下防止我的用户输入双精度或字符串并获得 InputMismatchException?我也不能使用 var 类型推断。我一直试图找到一种可能使用 hasNextInt() 方法或其他方法的方法,但据我所知,我会遇到同样的问题。

我是否必须使用 nextLine() 来解析作为整数输入传递的字符串?

在此先感谢您的帮助。

回答

简答

用于Integer.parseInt(input.nextLine())查找NumberFormatException.

没有 Try-Catch

如果您真的必须避免使用 try-catch,那么您input.hasNextInt()在尝试解析整数之前调用的想法input.nextInt()将起作用。

int userInt = 0;
if (input.hasNextInt()) {
  userInt = input.nextInt();
} else {
  System.out.println("That wasn't a valid int.");
  // Take whatever corrective action you want here.
}

长答案

如果您有计算器的 UI,那么您可以确保单击特定按钮只会将有效值发送回计算后端。但是,由于您似乎让您的用户在命令行上输入他们的值,因此没有办法将他们的键盘锁定为只能输入有效数字。因此,您必须自己测试他们输入的有效性。

潜在的增强

此外,当我试图从用户那里获取一个数字时,我喜欢循环并不断向他们询问一个有效的数字,而不是终止程序。考虑这样的事情。

Scanner input = new Scanner(System.in);
int userInt = 0;
boolean userIntReceived = false;

while (!userIntReceived) {
  try {
    userInt = Integer.parseInt(input.nextLine());
    userIntReceived = true;
  } catch (NumberFormatException e) {
    System.out.println("That wasn't a valid int. Please try again.")
  }
}

// Now you have a valid int from the user.

input.close();


以上是如何处理用户将无效类型输入扫描仪?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>