确定正确的数据类型

时间:2015-07-01 19:20:38

标签: java string integer return

以下代码未编译。

据我了解,dayCounter方法应该从早期代码传递dayCheck整数(这是主要方法?)。在dayCounter方法中,此整数将被称为dayNumber。字符串dayName将根据整数dayNumber的值分配一个值。然后行“return dayName;”应该返回字符串dayName作为dayCounter方法的输出。

我认为问题出在以下几行:

return dayName;

或使用以下行:

static int dayCounter(int dayNumber) {

我尝试将前者更改为:

static String dayCounter(int dayNumber) {

因为我认为这可能意味着dayCounter方法能够返回一个字符串 - 但这没有帮助。

我知道整数和字符串之间存在某种混淆。

class WhatDayIsIt {
    public static void main (String[] arguments) {

        int dayCheck = -1;

        if(arguments.length > 0)
            dayCheck = Integer.parseInt(arguments[0]);

        System.out.println("The day today is " + dayCounter(dayCheck));     

    } 

    static int dayCounter(int dayNumber) {

        String dayName;

        if (dayNumber == -1)
            dayName = "No day given";

        switch (dayNumber) {
            case 1:
                dayName = "Monday";
            case 2:
                dayName = "Tuesday";
            case 3:
                dayName = "Wednesday";
            case 4:
                dayName = "Thursday";
            case 5:
                dayName = "Friday";
            case 6:
                dayName = "Saturday";
            case 7:
                dayName = "Sunday";

        }

        return dayName;

    } 
}

2 个答案:

答案 0 :(得分:2)

static int dayCounter(int dayNumber) {表示您将返回int类型的值,但实际返回的是dayName,其类型为string。将方法定义更改为: static String dayCounter(int dayNumber){

您还需要更新您的开关案例,因为没有break语句,因此您的值会失败。 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

static String dayCounter(int dayNumber) {

        String dayName;

        switch (dayNumber) {
            case 1:
                dayName = "Monday";
                break;
            case 2:
                dayName = "Tuesday";
                break;
            case 3:
                dayName = "Wednesday";
                break;
            case 4:
                dayName = "Thursday";
                break;
            case 5:
                dayName = "Friday";
                break;
            case 6:
                dayName = "Saturday";
                break;
            case 7:
                dayName = "Sunday";
                break;
            default:
                dayName = "No day given";
                break;

        }

        return dayName;

    } 

答案 1 :(得分:0)

使dayCounter方法返回String:

static String dayCounter(int dayNumber) { ... }