java - 使用 Scanner 嵌套 if 语句的困惑
问题描述
所以这个程序我基本上错过了几件事:
- 确保工资不低于0
- 确保小时数不小于 40 并且大于 0。
我的问题是我不知道如何解决这个问题。最初我认为我可以在每个 If 语句的第一个 If 语句中添加一个 If 语句,但是在扫描之前存储在 scan 中的值不可用,这是在第一个 If 语句之后。我将如何发表这样的声明来检查这些?
这是代码:
import java.util.Scanner;
public class PayrollCC{
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
double wage=0;
int hours=0;
boolean bool = false;
final int MAXHOURS = 40;
do{
System.out.println("Please enter your hourly wage: ");
if(scan.hasNextDouble() && !scan.hasNextInt()){
wage = scan.nextDouble();
scan.nextLine();
bool = true;
}
else{
bool = false;
scan.nextLine();
}
} while(!bool);
do{
System.out.println("Please enter how many hours you have worked this week: ");
if(scan.hasNextInt()){
hours = scan.nextInt();
scan.nextLine();
if(hours > MAXHOURS && hours < 0){
bool = false;
}
bool = true;
}
else{
bool = false;
scan.nextLine();
}
} while(!bool);
double week = (hours*wage);
double total = (week);
double avg = (week);
System.out.println("Week's pay: $"+(week)+" Total pay: $"+(total)+" Average pay per week: $"+(avg));
}
}
解决方案
这是我将如何实现它。我不知道这是否对您完全有帮助,但如果没有,我很乐意回答有关它的任何问题。
import java.util.Scanner;
public class PayrollCC{
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
double wage = 0;
int hours = 0;
final int MAX_HOURS = 40;
//Get user's wage
do {
System.out.println("Please enter your wage: ");
wage = scan.nextDouble();
} while (wage < 0);
//Get user's hours worked
do {
System.out.println("Please enter how many hours you have worked this week: ");
hours = scan.nextInt();
} while ((hours > 40) || (hours < 0));
double week = (hours*wage);
double total = (week);
double avg = (week);
System.out.println("Week's pay: $"+(week)+" Total pay: $"+(total)+" Average pay per week: $"+(avg));
}
}
推荐阅读
- r - 为什么用 rgeom 更改 p 值不会给出预期的结果
- javascript - 我如何通过关闭来解决这个问题?
- php - 本地 WordPress 和 MAMP wp_remote_get():cURL 错误 60:SSL 证书问题:无法获取本地颁发者证书
- linux - Linux - 我应该考虑什么作为我的磁盘空间使用(表观大小或其他)?
- java - Hibernate 不从数据库返回第一条记录
- rust - 使用关联类型时不满足特征绑定
- android - 无法解析 ':app@debugUnitTest/compileClasspath' 的依赖关系:无法解析 androidx.legacy:legacy-support-v4:1.0.0
- jfr - 显式设置 JFR 事件的持续时间
- r - tidyr:将一列分成可变数量的列
- android - WebRTC 重新连接后断开连接 (Android)