java - 使用循环进行输入验证和异常处理

标签 java loops try-catch

如何使用循环进行输入验证以及 try 和 catch block 来捕获输入不匹配异常?

这是我的主要方法

import java.util.InputMismatchException;
import java.util.Scanner;

public class labBookFortyThree {
    public static void main(String[] args) {
        Scanner myInput = new Scanner(System.in);
        double circle, rect1, rect2, cyl1, cyl2;
        int input = 0;
        System.out.println("Press 1 to calc circle, 2 for rect, 3 for cyln");

        try {
            input = myInput.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Please enter a proper value");
        }

        if (input == 1) {
            System.out.println("enter radius");
            circle = myInput.nextDouble();
            System.out.println("area of circle is " + areas.area(circle));
        } else if (input == 2) {
            System.out.println("enter length and height");
            rect1 = myInput.nextDouble();
            rect2 = myInput.nextDouble();
            System.out.println("area of rect is " + areas.area(rect1, rect2));
        } else if (input == 3) {
            System.out.println("enter rad, height");
            cyl1 = myInput.nextDouble();
            cyl2 = myInput.nextDouble();
            int useless = 0;
            System.out.println("Area of cyl is " + areas.area(cyl1, cyl2, useless));
        }
    }
}

这是我的类区域

public class areas {
    public static double area(double rad) {
        double area = 3.14 * (rad * rad);
        return area;
    }

    public static double area(double width, double height) {
        double area = width * height;
        return area;
    }

    public static double area(double rad, double height, int useless) {
        double area = (3.14 * (rad * rad) * height);
        return area;
    }
}

我应该在哪里放置输入验证循环?有没有更好的办法?我可以在 catch 或 try block 中创造性地做些什么?

最佳答案

而不是

try {
  input = myInput.nextInt();
} catch (InputMismatchException e) {
  System.out.println("Please enter a proper value");
}

一种可能的方法是使用循环并检查您期望的输入,例如 1 到 3 之间的 int

int input = 0;
while(input < 1 || input > 3) {
  if (myInput.hasNextInt()) {
    input = myInput.nextInt();
  } else if (myInput.hasNext()) {
    System.out.println("Please enter a proper value");
    myInput.next();
  } else {
    System.err.println("No more input");
    System.exit(1);
  }
}
// input is 1,2 or 3. Or the program ended.

关于java - 使用循环进行输入验证和异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25041843/

相关文章:

java - 如何在android中提取hashmap的arraylist列表并循环遍历它?

php - Yii2 - fatal error ,try-catch 不工作

java - Try block 中的语句执行

java - 在 Java 中制作一个不可聚焦的窗口

php - 在 PHP 中从 while 循环构建单个数组时遇到问题

c++ - 这个 while 循环导致我的程序挂起

c# - 是否有理由两次抛出异常?

java - Maven 项目在 eclipse 中工作,但不能在命令行中工作

java - 使用 Java 中的 Apache Commons 为 CSV 生成字符串内容,而不是编写实际文件

java - 在java中使用imgscalr API调整图像大小