gpt4 book ai didi

java - 如何从 boolean 方法返回整数?

转载 作者:行者123 更新时间:2023-12-02 07:17:15 25 4
gpt4 key购买 nike

我在这里寻找类似的东西,但似乎没有任何帮助。我试图将输入 boolean 方法的值返回到我的测试程序。任何建议都将被排除在外。由于我的代码很长,我只会包含我认为相关的内容。

    public class SeasonCalculatorTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the month: ");
int month = in.nextInt();

System.out.print("Enter the day: ");
int day = in.nextInt();

SeasonCalculator calculator = new SeasonCalculator(month, day);

//TODO USE THE calculator (SeasonCalculator) TO CHECK FOR VALID MONTH AND VALID DAY.
// IF MONTH OR DAY IS NOT VALID PRINT ERROR MESSAGE.
// IF VALID PRINT OUT THE MONTH (IN STRING FORM, NOT INT FORM), THE DAY,
// AND THE SEASON THAT THE DAY IS IN

if(calculator.isValidMonth())
{
System.out.print(calculator.getMonth());
}
if(calculator.isValidDay())
{
System.out.print(" "+calculator.isValidDay()+" is in the "+ calculator.getSeason());
}
else
{
System.out.println("False");
}

}
}

我需要返回 int 值的方法是“isValidDay()”,代码如下:

public boolean isValidDay()
{
if ((month == 1 && day >= 1) && (month == 1 && day <= 31))
{
return true;
}
if ((month == 2 && day >= 1) && (month == 2 && day <= 29))
{
return true;
}
if ((month == 3 && day >= 1) && (month == 3 && day <= 31))
{
return true;
}
if ((month == 4 && day >= 1) && (month == 4 && day <= 30))
{
return true;
}
if ((month == 5 && day >= 1) && (month == 5 && day <= 31))
{
return true;
}
if ((month == 6 && day >= 1) && (month == 6 && day <= 30))
{
return true;
}
if ((month == 7 && day >= 1) && (month == 7 && day <= 31))
{
return true;
}
if ((month == 8 && day >= 1) && (month == 8 && day <= 31))
{
return true;
}
if ((month == 9 && day >= 1) && (month == 9 && day <= 30))
{
return true;
}
if ((month == 10 && day >= 1) && (month == 10 && day <= 31))
{
return true;
}
if ((month == 11 && day >= 1) && (month == 11 && day <= 31))
{
return true;
}
if ((month == 12 && day >= 1) && (month == 12 && day <= 31))
{
return true;
}
else
{
return false;
}
}

最佳答案

你可以做的是:

  • 如果参数无效,让构造函数抛出异常
  • 通过将月份的最大天数存储在数组中来检查该日期是否有效
  • 提供获取方法来访问月份/日期
class SeasonCalculator {
private static final int[] days = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
private final int month;
private final int day;

public SeasonCalculator(int month, int day) {
if (month < 1 || month > 12) {
throw new IllegalArgumentException("Not a valid month: " + month);
}
if (day < 1 || day > days[month - 1]) {
throw new IllegalArgumentException("Not a valid day: " + day + " for month " + month);
}
this.month = month;
this.day = day;
}

public int getMonth() {
return month;
}

public int getDay() {
return day;
}
}

关于java - 如何从 boolean 方法返回整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14790537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com