[英]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)
}
多個問題 :
;
在for
循環之后。 y
是不是在你的主要方法定義。 ;
y = (i/2)
HalfOfInt
i
。 另外,您應該堅持使用Java命名約定。 方法應以小寫字母開頭 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.