gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:28:33 25 4
gpt4 key购买 nike

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

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

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.hasNextDouble() 来验证它是数字,如果此扫描仪输入中的下一个标记可以解释为 double 值,则返回 true使用 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

关于java - 如何将用户输入限制为数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28236707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com