有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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);
    }
}

共 (2) 个答案

  1. # 1 楼答案

    在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;
        }
    }
    
  2. # 2 楼答案

    我建议换一个新的

    _sideA = input.nextDouble();
    

    _sideA = parseValue();
    

    移动

    Scanner input = new Scanner(System.in);
    

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

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

    您可能需要使用其他一些异常类型,在这种情况下,您需要确保也捕获该类型。同样,确保更新sideB以使用新函数