【问题标题】:Program won't return String程序不会返回字符串
【发布时间】:2015-10-12 22:17:34
【问题描述】:

所以我在编程课的介绍中被​​分配了一个问题。我对解决此问题的方法进行了一些研究,并且能够毫无错误地进行编译,但是其中一个规定是我必须返回一个字符串。这就是我把头撞到砖墙上的地方。我已经尝试了几种方法来解决这个问题,但我希望这里有人能发现我一直在努力解决的问题。

public class TellSeason {

    public static void main(String[] args) {
        season(5 , 12);
    }

    public static String season(int month , int day) {

        if ((month == 9 && day >=16)
            || month == 10
            || month == 11
            || (month == 12 && day <=15)) {
            return ("Fall");
        }
        else if ((month == 12 && day >=16)
                 || month == 1
                 || month == 2
                 ||(month == 3 && day <=15)) {
            return ("Winter");
        }
        else if ((month == 3 && day >=16)
                 || month == 4
                 || month == 5
                 ||(month == 6 && day <=15)) {
            return ("Spring");
        }
        else {
            return("Summer");
        }
    }
}

【问题讨论】:

  • | 的用途是什么?那不适合我。
  • 程序的返回值总是一个int。您确定要求不仅仅是将字符串打印到标准输出吗?
  • ||是“或”操作数。但是我能够完成问题
  • @Mureinik Java 程序没有返回值。
  • @DavidPulse 这是一个conditional-or operator。相当初级。

标签: java string return


【解决方案1】:

这样的?

public static void main(String[] args){
    System.out.println(season(5 , 12));
}

更多提示 - 您可以一起比较月份和日期

int idx = month * 100 + day;
if (idx <= 315 || idx >= 1216)
    return ("Winter");

if (idx >= 916) 
    return ("Fall");

if (idx >= 616) 
    return("Summer");

//if (idx >= 316) 
return ("Spring");

【讨论】:

    【解决方案2】:

    两件事,首先你没有对你的方法的结果做任何事情。基本上,您只需在 main 方法中调用 season 即可,而对结果不做任何事情。

    其次,查看你的 main 方法的方法签名。它明确指出main 具有返回类型void。这意味着,这个方法不能返回任何东西。您可以使用System.exit() 提供退出代码,但是,这仅限于整数返回代码。

    我强烈怀疑您真正追求的只是将结果打印到控制台的能力。也就是说,

    System.out.println(season(5,12));
    

    【讨论】:

    • 谢谢,我想我被问题的措辞误导了。这绝对是一个DUH!时刻
    • 欢迎您,相信我,这发生在我们所有人身上。如果我在编程中永远拥有一磅,那么我就拥有了。我会很富有;-)
    【解决方案3】:

    如果你想从你的 main 返回任何东西,那是不可能的。 但是如果你想显示你的结果,System.out.println 是你的方法

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 1970-01-01
      • 2014-02-14
      • 2010-11-11
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      相关资源
      最近更新 更多