簡體   English   中英

為什么我的方法不會返回任何內容?

[英]Why won't my method return anything?

這是我的代碼,當我去編譯並運行代碼時,它返回任何我不理解的內容,因為我在If和Else中有返回語句。

public class Program8
{
    public static void main(String[] args)
    {
        getMonth("02/12/96");
    }

    public static int getMonth(String date)
    {
        if(date.substring(0,1).equals("0")) 
        {
            return Integer.parseInt(date.substring(1,2));
        }
        else 
        {
            return Integer.parseInt(date.substring(0,2));
        }
    }
}

您的方法getMonth確實返回一個值,但它只是在main方法中被丟棄。

可能你想打印它,像這樣:

public static void main(String[] args){
    System.out.println(getMonth("02/12/96"));
}

或者記錄它,或者讓它以某種方式讓用戶可見(例如GUI),或者將它分配給這樣的變量:

public static void main(String[] args){
    int month = getMonth("02/12/96"); 
    // now `month` can be used for the subsequent operations/calculations
}

然后在進一步的計算中使用變量值。

你沒有輸出任何東西。 嘗試:

public static void main(String[] args){
    System.out.println(getMonth("02/12/96"));
}

您需要將返回的變量打印到控制台。

例如

public static void main(String[] args){
    System.out.println(getMonth("02/12/96"));
}

程序無法知道您是否要在控制台中打印月份。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM