Kor*_*aff 0 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));
}
}
Run Code Online (Sandbox Code Playgroud)
感谢您的时间。
我假设您正在使用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();
Run Code Online (Sandbox Code Playgroud)
输出,
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5228 次 |
| 最近记录: |