简体   繁体   English

如何在 INT 方法中不返回值?

[英]How to NOT return value in INT method?

When I run the code it returns:当我运行代码时,它返回:

31 and -1 31 和 -1

How can I get rid of -1?我怎样才能摆脱-1? Is there a way NOT to return in method INT?有没有办法在方法 INT 中不返回? I tried to return java.lang.Integer(null) but it gave me an error.我试图返回 java.lang.Integer(null) 但它给了我一个错误。 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.我几乎尝试了所有应该有的东西我还不知道。

This is because you are printing first in the method and then printing again the returned value of the method in y.这是因为您首先在方法中打印,然后在 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;
}

Is there a way NOT to return in method INT?有没有办法在方法 INT 中不返回?

Yea, sure.是的,当然。 Throw an exception.抛出异常。 For an example:例如:

if (month < 1 || month > 12) {
    throw new IllegalArgumentException("month value is out of range");
} 

(Hint: I noted a bug in your existing error checking. Look carefully at it when you rewrite it.) (提示:我注意到您现有错误检查中的一个错误。重写时仔细查看。)

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 .您可以在 Oracle Java 教程中阅读它: 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. Java 教程的那部分解释了什么是异常,如何以及何时抛出它们,如何捕捉它们,以及当你没有捕捉到它们时会发生什么。

Having said that, there are a few places where you are returning -1 .话虽如此,有几个地方您要返回-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.如果getDaysInMonth的输入有效,那么您应该始终能够计算“一个月中的天数”值。 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.最后,如果getDaysInMonthgetDaysInMonth(1, 2020)返回-1 ,则表明您在该方法的逻辑中存在错误。 I recommend you use a debugger to find it ... if you can't spot it by reading and logically analyzing your code.我建议您使用调试器来找到它……如果您无法通过阅读和逻辑分析您的代码来发现它。

Looking carefully at your function, as it is now, it will always return -1 and nothing else.仔细查看你的函数,就像现在一样,它总是返回 -1 而没有别的。

A function declared public static int getDaysInMonth(int month, int year) must return an int value, if it completes successfully .函数声明public static int getDaysInMonth(int month, int year)必须返回一个int值,如果它成功完成

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:这是永远不会返回 -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));
}

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 the brake statement and they will all work together to give the same result. Java 中的case是“fall through”,这意味着您不必一遍又一遍地编写相同的代码,您可以将具有相同结果的 case 放在另一个 case 下,而无需使用brake语句,它们将一起工作以提供相同的结果.

  • 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 the switch block.如果月份无效,则不执行case语句,代码将直接转到switch块之后的行。 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.任何抛出异常的函数都必须在函数头中声明它这样做,方法是添加throws子句并列出用逗号分隔的异常。

  • When you call a function that throws an exception, you must wrap it in try .. catrch block .当你调用一个抛出异常的函数时,你必须将它包装在try .. catrch block 中

Java methods can return only one type of result: https://www.javatpoint.com/method-in-java Java 方法只能返回一种类型的结果: 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.它可能具有原始数据类型、对象、集合、void 等。如果该方法不返回任何内容,则使用 void 关键字。

As a workaround:作为解决方法:

Use the wrapper class使用包装类

You can use the Integer class as a return type and return null.您可以使用Integer类作为返回类型并返回 null。 It's not much better than -1 but it indicates that nothing was returned.它并不比 -1 好多少,但它表明没有返回任何内容。

Invalid argument exception无效参数异常

Throw this: https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html it's what it's made for抛出这个: https : //docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html这是它的用途

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

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

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