如何将用户的输入限制为数值?

How to restrict input from user to a numeric value?

我一直在网上搜索,似乎找不到这个答案 那么有谁知道如何阻止用户在只允许输入数字的地方输入字母?

这是我的代码到目前为止的样子。

public static double payCalculator(double hours, double basePay)
{
    double totalPay; 
    double overTime = 8.00 * 1.5;
    while(hours < 0 | hours > 60) {
        System.out.println("Cannot work more than 60 hours a week");
        System.out.println("Hours Work?");
        hours = in.nextDouble();
    }
    while(basePay < 8) {
        System.out.println("Base Pay cannot be less than 8");
        System.out.println("Base Pay?");
        basePay = in.nextDouble();
    }
    if 
        (hours <= 40){
        totalPay = hours*basePay;
    }
    else {
        totalPay = ((hours - 40)*overTime) + (40*basePay);
    }
    return totalPay;

}
public static void main (String[] args) {

    System.out.println("Hours worked?");
    hours = in.nextDouble();
    System.out.println("Base Pay?");
    basePay = in.nextDouble();
    DecimalFormat df = new DecimalFormat("###.##");
    totalPay = payCalculator(hours, basePay);
    System.out.println("Total Pay is " + df.format(totalPay));       
}
}

感谢您的宝贵时间。

我假设您正在使用 Scanner 进行输入。

您可以使用 Scanner.hasNextDouble() 来验证它是数字,它 returns 如果此扫描器输入中的下一个标记可以使用 nextDouble() 方法。扫描仪不会前进超过任何输入。

考虑这个例子,它会一直要求输入,除非用户提供一个数字,

    Scanner sc = new Scanner(System.in);
    double dbl = 0.0;
    boolean isValid = false;
    while (isValid == false) {
        System.out.println("Input Number: ");
        // If input is number execute this,
        if (sc.hasNextDouble()) {
            dbl = sc.nextDouble();
            isValid = true;
            System.out.println("OK");
        }
        // If input is not a number execute this block, 
        else {
            System.out.println("Error! Invalid number. Try again.");
        }
        sc.nextLine(); // discard any other data
    }
    sc.close();

输出,

Input Number: 
adsads
Error! Invalid number. Try again.
Input Number: 
sdas
Error! Invalid number. Try again.
Input Number: 
hello
Error! Invalid number. Try again.
Input Number: 
hi
Error! Invalid number. Try again.
Input Number: 
2.0
OK