为什么我不能从Java中的两个函数返回值?

时间:2017-07-07 14:48:25

标签: java

Error description here

我可以从以下代码返回getMonth()或getYear()。

当两者都被调用时,会显示错误。

我已经尝试在计算日期函数中单独给出m和y的值,这非常有效! 有什么建议吗?

我是初学者,如果有一个微不足道的错误,我会道歉,虽然不应该依照我。

import java.util.Scanner;

public class Second_Java {

public static int getMonth() {

    int a;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the input for the required month: ");
    a = sc.nextInt(); // stored in 'a' locally

    while (a < 1 || a > 12) {

        a = -1;
        System.out.println(a);

    }
    sc.close();
    return a;
}

public static int getYear() {

    int b;
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the input for the required year: ");
    b = input.nextInt(); // stored in 'a' locally

    while (b < 1) {

        b = -2;
        System.out.println(b);

    }
    input.close();
    return b;
}

public static void calculateDays(int m, int y) {

    switch (m) {
    case 4:
    case 6:
    case 9:
    case 11:
        m = 30;
        System.out.println(m);
        break;
    case 2:
        if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {
            m = 29;
            System.out.println(m);
        } else {
            m = 28;
            System.out.println(m);
        }
        break;
    default: {
        m = 31;
        System.out.println(m);
    }

    }

}

public static void main(String[] args) {

    int m = getMonth();
    int y = getYear();
    calculateDays(m, y);
}

}

2 个答案:

答案 0 :(得分:1)

关闭扫描仪还会关闭它正在扫描的输入流 - 在本例中为System.in。因此,当您随后调用getYear()时,它会发现输入流System.in已经关闭。

避免这种情况的一种方法是在两种方法中使用相同的扫描程序,方法是将其作为参数传递给方法。

来自Java API docs for Scanner.close()

  

public void close()

     

关闭此扫描仪。

     

如果此扫描程序尚未关闭,那么如果其底层可读也实现了Closeable接口,则将调用可读的close方法。如果此扫描仪已关闭,则调用此方法将无效。

顺便说一下,getMonth()getYear()中循环的目的不明确。如果要继续扫描直到输入有效值,则需要在循环内包含对Scanner.nextInt()的调用。并考虑使用do-while语句,因为您知道要读取至少一个值。

答案 1 :(得分:0)

您可以这样做,只需将两个值定义为字段的对象,例如对于上述情况。

class MonthAndYear {
   public int month;
   public int year;
}

并且您的函数可以执行上述两种方法,并返回填充了月份和年份值的MonthAndYear实例。

在上述情况下,您的月份和年份显然是紧密联系在一起的,您正在(重新)定义某种Date类。

请注意,许多代码库都有Pair个对象(或类似对象)来处理这类事情。如果你正在使用Scala,你可以使用元组(例如像(month, year)

轻松地将这两个值结合在一起