【问题标题】:Format multiple if-else statements into methods将多个 if-else 语句格式化为方法
【发布时间】:2015-03-28 12:42:26
【问题描述】:

我有一个程序可以检查用户日期输入并显示下一个日期的输出。但是,我在程序中使用了多个 if-else 语句。

我想修改它,让它使用方法来进行计算,而不是重复的代码。

下面是我的代码示例,以三月和四月为例,一个是30天,一个是31天:

public class calDate{

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        boolean dateValid = false;
        int day = 0;
        int month = 0;
        int year = 0;
        int nextDay = 0
        int nextYear = 0;
        String nextMonth = "";
        boolean run=true;
        char again='Y';

while(run)
        {

        System.out.print("Day: ");
        day = scan.nextInt();

        System.out.print("Month: ");
        month = scan.nextInt();

        System.out.print("Year: ");
        year = scan.nextInt();

while (month < 1 && month > 12) //check if month is within 1 to 12
        { 
            dateValid = false;
        }

if ((month == 3) && (day >= 1 && day <= 31)) 
        {
            dateValid = true;
            nextDay = day + 1;
            nextMonth = " March ";
            nextYear = year;

            if (day == 31) {
                nextDay = 1;
                nextMonth = " April ";
                nextYear = year;
            }
        } 

        else if ((month == 4) && (day >= 1 && day <= 30)) 
        {
            dateValid = true;
            nextDay = day + 1;
            nextMonth = " April ";
            nextYear = year;

            if (day == 30) 
            {
                nextDay = 1;
                nextMonth = " May ";
                nextYear = year;
            }  
        }
if (dateValid){
        System.out.println("Tomorrow's date: " + nextDay + nextMonth + nextYear);
        System.out.print("Continue?(Y/N)  ");
        again = scan.next().charAt(0);
        if (again=='Y')
        {
        run=true;
        System.out.println("");
        }
        if (again=='N')
        {
        run=false;
        }
        if ((again != 'N')&&(again!='Y'))
        {
        System.out.println("Invalid input. Ending program."); 
            run=false;
        }   
        }

        else{
        System.out.println("Invalid input. Continue?(Y/N)  ");
        again = scan.next().charAt(0);
        if (again=='Y')
        {
        run=true;
        System.out.println("");
        }
        if (again=='N')
        {
        run=false;
        }
        if ((again != 'N')&&(again!='Y'))
        {
        System.out.println("Invalid input. Ending program.");
        run=false;
        }
    }
   }

有很多重复值,如dateValidnextDaynextMonthnextYear。如何格式化我的代码,以便我可以将语句放入单独的方法中?谢谢。

【问题讨论】:

  • 您的while 逻辑似乎不正确。如果您输入的月份不在 1 到 12 的范围内,您将永远无法脱离循环。这可能不是你想要的。
  • 嗨@Arjan,我做了一些更改,如果他/她希望继续,如果检测到无效输入,我的程序将提示用户输入
  • 但您仍然有 while (month &lt; 1 &amp;&amp; month &gt; 12) 行。您可能希望在此处使用 if 语句。

标签: java if-statement methods


【解决方案1】:

我的第一个建议是将月份变成一个枚举。这样你就可以在一个类中封装与月份相关的所有逻辑:

enum Month {
    JAN ("Jan", 31),
    FEB ("Feb", 28), 
    ....
    DEC ("Dec", 31);

    private final String monthName;
    private final int daysInMonth;

    private Month(String monthName, int daysInMonth) {
        this.monthName = monthName;
        this.daysInMonth = daysInMonth;
    }

    public String getName() {
        return monthName;
    }

    public static Month monthWithNumber(int monthNumber) {
        if (monthNumber < 1 || monthNumber > 12) 
            throw new IllegalArgumentException();
        return values()[monthNumber - 1];
    }

    public isLegalDay(int day) {
        return day > 0 && day <= daysInMonth;
    }

    public isLastDayInMonth(int day) {
        return day == daysInMonth;
    }

    public Month nextMonth() {
        return values[(ordinal() + 1) % 12];
    }
}

这会立即删除您的大部分 if 语句并将它们替换为:

Month month = Month.monthWithNumber(monthNumber);
if (month.isLegalDay(dayNumber)) {
    ....
    if (month.isLastDayInMonth(dayNumber)) {
        nextMonth = month.nextMonth().getName();
        nextDay = 0;
    }
}

【讨论】:

    【解决方案2】:

    我建议您使用给定的输入值构建一个字符串,使用 SimpleDateFormat 解析生成的字符串,然后捕获 ParseException 以更新您的 dateValid 布尔值。

    这也可以让您更轻松地添加一天。

    【讨论】:

    • 如果这不是作业(我怀疑是),使用 JSR-310/Java 8 中的 LocalDate 可能会更好。
    • @PeterLawrey 你的预感是正确的,这是我的作业。我不允许使用LocalDate或任何Datelibraries`。
    • @RUiHAO 但是,他们不必知道您检查您的代码是否与 LocalDate 做同样的事情,您甚至可以以类似的方式构建您的代码,即您会学到很多好的编程实践通过这样做并确信您的代码是正确的。
    【解决方案3】:

    我建议你使用像 int[] daysInTheMonth = { 31. 28, ...String[] monthName = ",Jan,Feb,Mar".split(","); 这样的数组,在你的代码中使用数据会使它比现在短得多,即使你处理了所有月份。

    包含isLeapYear(year) 方法会很有用。

    出于测试目的,我建议您确保获得与 JSR-310 库相同的结果。虽然我假设你不能直接使用这个库,但你可以用它来测试你的代码是否正确。

    【讨论】:

      【解决方案4】:

      我可能会创建方法getNextDay()getMonthForNextDay()getYearForNextDay()。他们将用户输入作为参数,并分别简单地返回正确的日、月和年。您也可以将其与 Peter Lawreys 的回答结合起来。

      【讨论】:

      • 谢谢@Arjan。我将尝试理清如何创建单独的方法,因为我对在我的方法中放入什么感到很困惑。谢谢!
      猜你喜欢
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多