首页 > 解决方案 > 使用 Scanner 嵌套 if 语句的困惑

问题描述

所以这个程序我基本上错过了几件事:

我的问题是我不知道如何解决这个问题。最初我认为我可以在每个 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));



}
}

标签: javajava.util.scanner

解决方案


这是我将如何实现它。我不知道这是否对您完全有帮助,但如果没有,我很乐意回答有关它的任何问题。

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

    }
}

推荐阅读