英文:
How to NOT return value in INT method?
问题
当我运行代码时,它返回:
31 和 -1
如何摆脱 -1?有没有一种方法可以不在 INT 方法中返回?我尝试返回 java.lang.Integer(null) 但是它给了我一个错误。我认为我使用错了。
以下是代码:
package com.company;
public class Main {
public static void main(String[] args) {
int y = getDaysInMonth(1, 2020);
System.out.println(y);
}
public static boolean isLeapYear(int year) {
if (year > 1 && year < 9999) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return true;
}
return false;
}
return false;
}
public static int getDaysInMonth(int month, int year) {
if ((month < 1 || month > 12) && (year < 1 || year > 9999)) {
return -1;
} else if (!isLeapYear(year)) {
switch (month) {
case 1:
System.out.println(31);
break;
case 2:
System.out.println(28);
break;
case 3:
System.out.println(31);
break;
case 4:
System.out.println(30);
break;
case 5:
System.out.println(31);
break;
case 6:
System.out.println(30);
break;
case 7:
System.out.println(31);
break;
case 8:
System.out.println(31);
break;
case 9:
System.out.println(30);
break;
case 10:
System.out.println(31);
break;
case 11:
System.out.println(30);
break;
case 12:
System.out.println(31);
break;
default:
return -1;
}
} else if (isLeapYear(year)) {
switch (month) {
case 1:
System.out.println(31);
break;
case 2:
System.out.println(29);
break;
case 3:
System.out.println(31);
break;
case 4:
System.out.println(30);
break;
case 5:
System.out.println(31);
break;
case 6:
System.out.println(30);
break;
case 7:
System.out.println(31);
break;
case 8:
System.out.println(31);
break;
case 9:
System.out.println(30);
break;
case 10:
System.out.println(31);
break;
case 11:
System.out.println(30);
break;
case 12:
System.out.println(31);
break;
default:
return -1;
}
} else return -1;
return -1;
}
}
我尝试了几乎所有的方法,可能还有些我不知道的东西。
英文:
When I run the code it returns:
31 and -1
How can I get rid of -1? Is there a way NOT to return in method INT? I tried to return java.lang.Integer(null) but it gave me an error. I think I used it in a wrong way.
Here is the code:
package com.company;
public class Main {
public static void main(String[] args) {
int y = getDaysInMonth(1, 2020);
System.out.println(y);
}
public static boolean isLeapYear(int year) {
if (year > 1 && year < 9999) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
return true;
}
return false;
}
return false;
}
public static int getDaysInMonth(int month, int year) {
if ((month < 1 || month > 12) && (year < 1 || year > 9999)) {
return -1;
} else if (!isLeapYear(year)) {
switch (month) {
case 1:
System.out.println(31);
break;
case 2:
System.out.println(28);
break;
case 3:
System.out.println(31);
break;
case 4:
System.out.println(30);
break;
case 5:
System.out.println(31);
break;
case 6:
System.out.println(30);
break;
case 7:
System.out.println(31);
break;
case 8:
System.out.println(31);
break;
case 9:
System.out.println(30);
break;
case 10:
System.out.println(31);
break;
case 11:
System.out.println(30);
break;
case 12:
System.out.println(31);
break;
default:
return -1;
}
} else if (isLeapYear(year)) {
switch (month) {
case 1:
System.out.println(31);
break;
case 2:
System.out.println(29);
break;
case 3:
System.out.println(31);
break;
case 4:
System.out.println(30);
break;
case 5:
System.out.println(31);
break;
case 6:
System.out.println(30);
break;
case 7:
System.out.println(31);
break;
case 8:
System.out.println(31);
break;
case 9:
System.out.println(30);
break;
case 10:
System.out.println(31);
break;
case 11:
System.out.println(30);
break;
case 12:
System.out.println(31);
break;
default:
return -1;
}
} else return -1;
return -1;
}
}
I tried almost everything there should be something that I don't know yet.
答案1
得分: 2
这是因为你在方法中先进行打印,然后又打印了方法返回的值 y。
与其每次进行打印,不如尝试返回这些值。而且,你编写的程序可以写得更加高效。以下是一个示例:
public static int getDays(int monthNumber, int yearNumber)
{
if (monthNumber == 2 && !isLeapYear(yearNumber))
return 28;
else if (monthNumber==2)
return 29;
else if ((monthNumber >= 1) && (monthNumber <= 7) && (monthNumber % 2 ==1))
return 31;
else if ((monthNumber >= 8) && (monthNumber %2==0))
return 31;
else
return 30;
}
英文:
This is because you are printing first in the method and then printing again the returned value of the method in y.
Instead of printing every time, try returning the values. Also the program you have written could be written much efficiently.
Here is an example :
public static int getDays(int monthNumber, int yearNumber)
{
if (monthNumber == 2 && !isLeapYear(yearNumber))
return 28;
else if (monthNumber==2)
return 29;
else if ((monthNumber >= 1) && (monthNumber <= 7) && (monthNumber % 2 ==1))
return 31;
else if ((monthNumber >= 8) && (monthNumber %2==0))
return 31;
else
return 30;
}
答案2
得分: 1
> 有没有方法在 INT 类型的方法中不返回值?
是的,当然可以。抛出一个异常。例如:
if (month < 1 || month > 12) {
throw new IllegalArgumentException("月份值超出范围");
}
(提示:我在您现有的错误检查中注意到了一个 bug。在重写时仔细查看它。)
抛出异常会导致方法在不返回任何结果的情况下终止。即使方法签名指定应该返回结果。您可以在 Oracle Java 教程中了解更多:https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html。Java 教程的这部分解释了异常是什么,何时以及如何抛出异常,如何捕获异常,以及不捕获异常时会发生什么。
话虽如此,有几个地方您正在返回 -1
。您需要仔细检查每个地方,以决定它是否可能发生。如果 getDaysInMonth
的输入有效,则应始终能够计算出“月份的天数”值。而且您只需要在一个地方检查参数。
我的建议是在方法开始时检查参数值。然后,可以在假定参数有效的情况下编写方法的其余部分。
最后,如果 getDaysInMonth(1, 2020)
返回 -1
,则表示您的方法逻辑存在 bug。我建议您使用调试器找出 bug……如果您无法通过阅读和逻辑分析代码找到 bug 的话。
英文:
> Is there a way NOT to return in method INT?
Yea, sure. Throw an exception. For an example:
if (month < 1 || month > 12) {
throw new IllegalArgumentException("month value is out of range");
}
<sup>(Hint: I noted a bug in your existing error checking. Look carefully at it when you rewrite it.)</sup>
Throwing an exception causes the method to terminate without returning any result. Even if the method signature says that a result should be returned. You can read about it in the Oracle Java Tutorials: https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html. That part of the Java Tutorials explains what exceptions are, how and when to throw them, how to catch them, and what happens when you don't catch them.
Having said that, there are a few places where you are returning -1
. You need to check each one carefully to decide if it is actually possible. If the inputs to getDaysInMonth
are valid, then you should always be able to compute a "days in the month" value. And you should only need to check the arguments in one place.
My recommendation would be check the argument values at the start of the method. The rest of the method can then be coded on the assumption that the arguments are valid.
Finally, if the getDaysInMonth
is returning -1
for getDaysInMonth(1, 2020)
that indicates that you have a bug in the logic of the method. I recommend you use a debugger to find it ... if you can't spot it by reading and logically analyzing your code.
答案3
得分: 1
看一下你的函数,目前它将始终返回-1,除此之外没有其他内容。
声明为 public static int getDaysInMonth(int month, int year)
的函数必须返回一个 int
值,如果它成功执行。
唯一可能不返回值而退出的情况是抛出异常。
因此,我假设你的函数需要返回该月的天数,而不仅仅是打印出来。
以下是相应的代码,它不会返回-1,也不会返回除了 28、29、30、31 之外的任何值:
public static int getDaysInMonth(int month, int year) throws IllegalArgumentException {
if (year < 1 || year > 9999) {
throw new IllegalArgumentException(String.format("Invalid year %d must be between 1 and 9999", year));
}
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println(31);
return 31;
case 2:
if (isLeapYear(year)) {
System.out.println(29);
return 29;
} else {
System.out.println(28);
return 28;
}
case 4:
case 6:
case 9:
case 11:
System.out.println(30);
return 30;
}
throw new IllegalArgumentException(String.format("Invalid month %d must be between 1 and 12", month));
}
注意以下更改:
-
在 Java 中,
case
是"fall through",这意味着你不必一遍又一遍地编写相同的代码,你可以将具有相同结果的 case 放在一起,无需使用break
语句,它们将一起工作以产生相同的结果。 -
在函数的开头,我们只检查年份是否有效。如果月份无效,
case
语句将不会执行,代码将直接进入switch
块之后的行。此时我们知道月份无效,所以无需检查,直接抛出异常。 -
任何抛出异常的函数都必须在函数头中声明,通过添加
throws
子句,并列出逗号分隔的异常。 -
当调用抛出异常的函数时,必须将其包装在
try ... catch
块 中。
英文:
Looking carefully at your function, as it is now, it will always return -1 and nothing else.
A function declared public static int getDaysInMonth(int month, int year)
must return an int
value, if it completes successfully.
The only case it may exit without returning a value is by throwing an exception.
So, I am going to assume your function needs to return the number of day in the month and not just print it.
Here is the code for that which will never return -1, or any value other than 28, 29, 30, 31:
public static int getDaysInMonth(int month, int year) throws IllegalArgumentException {
if (year < 1 || year > 9999) {
throw new IllegalArgumentException(String.format("Invalid year %d must be between 1 and 9999", year));
}
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println(31);
return 31;
case 2:
if (isLeapYear(year)) {
System.out.println(29);
return 29;
} else {
System.out.println(28);
return 28;
}
case 4:
case 6:
case 9:
case 11:
System.out.println(30);
return 30;
}
throw new IllegalArgumentException(String.format("Invalid month %d must be between 1 and 12", month));
}
Note the following changes:
-
case
in Java is "fall through" which means you don't have to write the same code over and over, you can put cases with same result one below the other without thebrake
statement and they will all work together to give the same result. -
At the beginning of the function we only check if the year is valid. If the month is invalid non of the
case
statements will execute and the code will go directly to the line after theswitch
block. At that point we know the month is not valid, so no need to check, just trow the exception. -
Any function that throws an exception must declare that it does so in the function header, by adding
throws
clause and listing the exceptions separated by commas. -
When you call a function that throws an exception, you must wrap it in
try .. catrch
block.
答案4
得分: 0
Java方法只能返回一种类型的结果:https://www.javatpoint.com/method-in-java
返回类型:返回类型是方法返回的数据类型。它可以是原始数据类型、对象、集合、void等。如果方法不返回任何内容,我们使用void关键字。
作为一种解决方法:
使用包装类
您可以使用Integer
类作为返回类型并返回null。虽然不比-1好多少,但它表明没有返回任何内容。
无效的参数异常
抛出此异常:https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html,它就是为此而生的。
default:
throw new IllegalArgumentException("无效的月份值 - 超出范围");
创建枚举
创建枚举类型,并将其作为您方法的参数。这样就不会有任何方式出现未知值。
public enum Month {
January(1), February(2), March(3), April(4), May(5), June(6), July(7), August(8), September(9), October(10), November(11), December(12)
}
英文:
Java methods can return only one type of result: https://www.javatpoint.com/method-in-java
> Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword.
As a workaround:
Use the wrapper class
You can use the Integer
class as a return type and return null. It's not much better than -1 but it indicates that nothing was returned.
Invalid argument exception
Throw this: https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html it's what it's made for
default:
throw new IllegalArgumentException("Invalid month value - out of range");
Create enum
Create an enum type and have it as a parameter in your method. That way there won't be any way to have an unknown value.
public enum Month {
January(1), February(2), March(3), April(4),May(5),June(6), July(7), August(8), September(9), October(10), November(11), December(12)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论