簡體   English   中英

打印一個Integer及其一半從main方法調用它

[英]Printing an Integer and their half calling it from main method

我只是開始學習Java。 我正在練習如何打印和半整數

我已經定義了main方法,對於halfing方法,我也已經在同一類中定義了它,但是它不會編譯。 有什么建議么? 這是我的代碼

public class IntAndHalf {

    public static void main(String[] args) {
        double y;
        for (int i = 1; i <= 20; i++) {
            System.out.println(i + " " + y);
        }
    }
    public static double halfOfint(int i){
        for (i = 0; i <= 20; i++){
            y = i/2;
            return (y);
        }
    }
}

暗示

您的代碼中有很多問題:

  • y在您的主要方法中未定義
  • i已在您的方法中聲明,因此您不必在循環中再次聲明它(int i = 0;)只需使用它(i = 0;)
  • 你的小姐; y = (i/2)的末尾y = (i/2)
  • 當你做; 在循環結束時,不會for(int i = 1; i <= 20; i++ );執行下一個塊
  • 您必須在方法的最后而不是在循環中return(y)

更正這種錯別字,您的代碼將被編譯,這是您永遠不會調用方法HalfOfInt的另一件事,因此不要等待從該方法中獲取信息,您必須調用main方法。


編輯

在這種情況下,您的代碼應如下所示:

public static void main(String[] args) {
    for (int i = 1; i <= 20; i++) {
        System.out.println(i + "-" + HalfOfInt(i));
        //                              ^-----------call your method which
                                                  //take an int and return the (i/2)
        //                 ^-------------------------Print your value
    }
}

public static double HalfOfInt(int i) {
    return (double) i / 2;//<<----------- no need to use a loop just return (i/2)
}

多個問題

  1. 有一個; for循環之后。
  2. y不是在你的主要方法定義。
  3. 你想念一個; y = (i/2)
  4. 你永遠不會打電話給HalfOfInt
  5. 你兩次宣布i

另外,您應該堅持使用Java命名約定。 方法應以小寫字母開頭

暫無
暫無

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

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