繁体   English   中英

创建一个在一个月中打印正确天数的输入法/ Int不能转换为字符串

[英]Creating a input method that prints right amount of days in a month/Int can't be converted into string

对于我的代码,我应该设置一个方法来询问月份的参数,然后打印出该月的正确天数。

当用户输入一个月时,我已经为每个月的每一天开发了 if 语句,但是,我不断收到一条消息,说int cannot be converted into string

我被告知我应该返回天数

[示例 1 月应返回 31]

但是我不完全确定如何做到这一点。 我没有尝试打印“31”,而是输入“return 31”?

import java.util.*;

public class findDays{
    public static String monthDays(int month){
        Scanner key = new Scanner(System.in);
        System.out.println("Type a month");
        month = key.nextInt();

        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) 
        {
            System.out.println("31");
        }
        else if(month == 2)
        {
            System.out.println("28");
        }
        else
        {
            System.out.println("30");
        }
   }
}

无需传递参数,使用java.time.*库可以提供很大帮助。

这是一个替代上述代码的建议,指定该方法是否返回闰年一个月的天数也可以增强功能。 如果闰年,二月份的天数可能会有所不同:

public static String monthDays(boolean isLeapYear) {
    int month;
    Scanner key = new Scanner(System.in);
    System.out.println("Type a month (a number in range of 1 to 12)");
    month = key.nextInt();
    if (month > 12 || month < 1)
        throw new IllegalArgumentException("The month number is invalid.");
    int thisYear = LocalDate.now().getYear();
    YearMonth yearMonth;
    int year = 0;
    if (isLeapYear) {
        if (Year.of(thisYear).isLeap())
            year = thisYear;
        else {
            for (int i = 1; i < 4; i++)
                if (Year.of(thisYear + i).isLeap())
                    year = thisYear + i;
        }
    } else {
        if (Year.of(thisYear).isLeap())
            year = thisYear + 1;
        else
            year = thisYear;
    }
    yearMonth = YearMonth.of(year, month);
    System.out.println("Inserted month: " + yearMonth.getMonth());
    int monthDays = yearMonth.lengthOfMonth();
    System.out.println("Number of days in month: " + monthDays);
    return String.valueOf(monthDays);
}

值得注意的是,在您的方法和建议的方法中,都需要确定年份,以便计算一个月中的天数会更准确。

首先,我们可以将年份设置为 currentYear 并根据leapYear 标志以及今年是否是闰年,我们将找出插入月份的天数。

希望能有所帮助。

要从方法返回值,您将使用return关键字后跟要返回的任何值,在您的情况下,您只是打印每个月的值,如果要返回它,请将其更改为

if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) 
        {
            System.out.println("31");
            return "31";
        }

这将打印该值,然后返回它。 你也可以实现一个switch case ,在这种情况下它比 if 语句更快更干净:

switch(month) {
    case 1:
    case 3:
    case 5:
    //.... all your 31 day months here
    return 31;

    case 2:
    return 28;
    default: 
    return 30;
}

default 关键字意味着,如果值不匹配任何 case 子句,则将执行默认值,类似于代码中的else

如果您想了解更多相关信息,本文将更详细地解释 switch 语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM