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

时间:2015-01-30 13:12:41

标签: java input java.util.scanner

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

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

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

感谢您的时间。

1 个答案:

答案 0 :(得分:3)

我假设你正在使用Scanner来接受输入。

您可以使用Scanner.hasNextDouble()验证它是否为数字,如果使用double方法将此扫描仪输入中的下一个标记解释为nextDouble()值,则返回true。扫描仪不会超过任何输入。

考虑这个例子,它会继续询问输入,除非用户提供了一个数字,

    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
相关问题