2014-10-31 154 views
-1

可以說我有一個主要的課程,我的主要課程是用它來運行的。我怎樣才能打電話給另一個班級

public calss Main{ 
    public static void main(String[] args){ 
     System.out.print("input Length "); 
     a = in.nextInt(); 
     System.out.print("input Height "); 
     b = in.nextInt(); 
     ... 
     (The code that goes in between?) 
     ... 
     System.out.println("output"); 
    } 
} 

如何使用在側另一個類,並輸入它我的第一類可說,如果它是一個簡單的計算類像

pubic class Math{ 
    output = a*b 
} 

,並有一個像這樣的輸入和輸出:

input Length 2 
input Height 3 
6 

順便說一句,不投票給我,因爲我是noob!共同爲什麼你這樣做? XD

+3

可能是值得的通過這些:http://docs.oracle.com/javase/tutorial/java/index.html – FelixMarcus 2014-10-31 14:49:03

回答

2

就這麼簡單。

public class Test{ 
    public int multiplication(int a, int b){ 
    return a*b; 
    } 

    public static void main(String[] args){ 
     System.out.print("input Length "); 
     a = in.nextInt(); 
     System.out.print("input Height "); 
     b = in.nextInt(); 
     ... 
     Test t = new Test(); 
     System.out.println(t.multiplication(a,b)); 
    } 
} 
+0

這個答案假設你想要一個類'Test'的實例來處理 - 沒有必要這樣做,因爲乘法是無國籍的。在這個例子中,因爲它與主方法在同一個類中,所以我建議將它稱爲靜態函數。 – 2014-10-31 14:50:31

+0

解決方案的解釋會很好 – 2014-10-31 14:52:53

+0

此外,代碼不會編譯。 – 2014-10-31 14:56:18

1

你在混淆類和方法。

如果你想把你的計算方法在一個類

例如,

public class MyCalc { 
    public static int calculate(int a, int b) { 
     return a*b; 
    } 
} 

然後,你可以調用從功能與你的主

public static void main(String[] args) { 

    // something 


    int result = MyCalc.calculate(1,2); 
} 

這就是你如何使用靜態功能於一身的工具類modularise一些功能。這有幫助嗎?

1

你的第二課也可能有字段和方法。對於你的例子,當你執行兩個整數的乘法時,你的Math類應該有一個方法,它應該接收這些整數作爲參數。下面是它的一個小例子:

public class Math { 
    //declaring the method as static 
    //no need to create an instance of the class to use it 
    //the method receives two integer arguments, a and b 
    //the method returns the multiplication of these numbers 
    public static int multiply(int a, int b) { 
     return a * b; 
    } 
} 

但要小心,不要與命名內置類的在Java中,同名類**在java.lang包專班。是的,Java中有一個內置的Math類。

所以,這將是最好的類重命名爲這樣的事情:

public class IntegerOperations { 
    public static int multiply(int a, int b) { 
     return a * b; 
    } 
} 

你會像這樣使用(修復當前的代碼後):

public class Main { 
    public static void main(String[] args) { 
     //Use a Scanner to read user input 
     Scanner in = new Scanner(System.in); 

     System.out.print("input Length "); 
     //declare the variables properly 
     int a = in.nextInt(); 
     System.out.print("input Height "); 
     int b = in.nextInt(); 

     //declare another variable to store the result 
     //returned from the method called 
     int output = Operations.multiply(a, b); 

     System.out.println("output: " + output); 
    } 
} 
+0

哦,對了,我忘記了數學課,謝謝你,雖然很有幫助! – 2014-10-31 14:53:56