如何在使用程序时不让用户使用0?

时间:2016-06-28 20:21:29

标签: java exception try-catch

我必须创建一个计算三角形斜边的程序。它只能使用数字,如果给定的输入不是数字,那么它应该抛出异常。我能够做到这一点,但是我希望用户无法输入0,因为0的三角形边面根本没有三角形。我尝试了陈述,但我不认为我正确使用它们。请帮忙!

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

public class handleexceptions1{
    public static void main(String[] args) {

        boolean repeat = true;
        double _sideA = 0;
        while (repeat) {
            try {
                Scanner input = new Scanner(System.in);
                System.out.println("Please enter side A: ");
                _sideA = input.nextDouble();

                repeat = false;
            } catch (InputMismatchException e) {
                System.out.println("Error! Please enter a valid number!");
            }
        }
        boolean repeat2= true;
        double _sideB = 0;
        while (repeat2){
            try {
                Scanner input = new Scanner(System.in);
                System.out.println("Please enter side B: ");
                _sideB = input.nextDouble();
                repeat2= false;
            } catch (InputMismatchException e) {
                System.out.println("Error! Please enter a valid number!");
            }
        }
        double hyptonuse = Math.sqrt((_sideA*_sideA) + (_sideB*_sideB));
        System.out.println("Side C(the hyptonuse) is: "+ hyptonuse);
    }
}

3 个答案:

答案 0 :(得分:0)

在try {}范围内检查您的数字是否大于0.如果是,请重复= false:

try {
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter side A: ");
    _sideA = input.nextDouble();
    if (_sideA > 0){
       repeat = false;
    }
}

答案 1 :(得分:0)

您可以将其替换为'repeat = false'行:

if(_sideA == 0){
repeat = true;
} else {
repeat = false;
}

为每个while循环执行此操作。

答案 2 :(得分:0)

我建议更换

_sideA = input.nextDouble();

_sideA = parseValue();

移动

Scanner input = new Scanner(System.in);

在新的辅助函数中,parseValue()如下所示:

private double parseValue() throws InputMismatchException
{
    Scanner input = new Scanner(System.in);
    double retVal = input.nextDouble();
    if (retVal <= 0)
    {
        throw InputMismatchException;
    }

    return retVal;
}

您可能希望使用其他一些Exception类型,在这种情况下,您还需要确保捕获该类型。同样,请确保更新sideB以使用新功能。