2014-10-31 152 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