2013-01-23 75 views
-2

我在我的教科書的問題,說:Java的布爾方法

寫方法多采用兩個整數作爲參數,並返回true,如果第一個整數整除 均勻地通過第二個(即劃分後沒有剩餘);否則,方法應該 返回false。將此方法合併到允許用戶輸入值以測試 方法的應用程序中。

,我寫了這個代碼,但它不工作:

public class project1 { 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     int a, b; 
     System.out.println("enter the first number"); 
     a = input.nextInt(); 

     System.out.println("enter the first number"); 
     b = input.nextInt(); 
    } 

    public static boolean multiple(int g, int c) { 

     int g, c; 

     if (g % c = 0) { 
      return true; 
     } else { 
      return false; 

     }; 
    } 
} 
+1

串「不工作」是不是在Java中內置的錯誤消息。 – 2013-01-23 07:13:18

+0

你的代碼甚至不會編譯。 – Maroun

+0

@assylias:'==='在javascript中有效,不在java中,我認爲你有一個錯字:) –

回答

1

首先,你不需要在功能multiple再次聲明gc(這是一個錯誤)。其次,你根本沒有調用函數,你只是實現了它。和其他人一樣,你需要有==而不是=

public static void main(String[] args) { 
    Scanner input = new Scanner (System.in); 
    int a,b; 
    System.out.println("enter the first number"); 
    a=input.nextInt(); 

    System.out.println("enter the first number"); 
    b=input.nextInt(); 

    boolean result = multiple(a,b); 
    System.out.println(result); 
} 

public static boolean multiple (int g,int c){ 
    if (g%c==0){ 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 

請注意,你可以有multiple對只有一個線較短的版本:return g%c==0;

5
//int g, c; 
^^ 

刪除此行..


if (g%c==0){ 
     ^

您需要使用==檢查平等。


實際上,你可以做以下,以減少幾行以及..

public static boolean multiple(int g, int c) { 
    return g%c == 0; 
} 
1

有在你的方法錯誤太多。它實際上應該是這樣的:

public static boolean multiple(int g, int c) { 
    return g % c == 0; 
} 
0

你聲明的變量除了=問題兩次。試試這個:

所有的
public static boolean multiple(int g, int c) { 
    return g % c == 0; 
}