繁体   English   中英

我如何在另一个类中调用以下方法? 爪哇

[英]How would I call the following methods in another class? java

import java.io.IOException;
import java.util.*;

public class calling {


public static int num1() {
int x;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number called x: ");
x=scanner.nextInt();
return x;    
}

public static int num2() {
int y;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number called y: ");
y=scanner.nextInt();
return y;    
}

public static String operand() {
Scanner input = new Scanner (System.in);
String s;
System.out.println("What process would you like to do? *, /, + or - ?");
s=input.next();
return s;
}

public static void calculation(int x, int y, String s) {
String t;
Scanner input = new Scanner(System.in);


if (s.equals("*")) {
System.out.println("\nThe product of these numbers is:" + (x*y));}
else 
if (s.equals("+")) {
System.out.println("\nThe sum of these numbers is: " + (x+y));}

System.out.println("\nDo you want x or y to be the dividor/subtractor?: ");
t=input.next();

if (t.equals("y") || t.equals("Y") ) {

if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is:  " + (x/y));}
else 
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + (x-y));}}

else 
if (t.equals("x") || t.equals("X")){

if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (y/x));}
else 
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + ((y-x)));}}
}

public static void  main (String [] args) throws IOException {


int x1=num1();
int y1=num2();
String s1=operand();
calculation(x1, y1, s1);




}

}

我如何将这些方法调用到新类中,以便可以从中运行程序? 我知道通常您会放置class.nameofmethod();的名称。 但是我该如何传递参数? 我是Java的初学者,所有帮助将不胜感激! 在此先感谢大家。

举个例子:

int x = calling.num1();
System.out.println(x);

...将num1()方法的结果存储在x中,然后打印出x的内容。

在参数方面:

calling.calculation(4,5,"+");

您需要问的一个事实表明,您可能应该去阅读并继续学习一些非常基础的Java教程,例如此处的一个: http : //download.oracle.com/javase/tutorial/getStarted/index。 html-根本不是攻击,只是关于如何最好地扩展您的知识的建议。

没有参数要传递,因为所有方法都是无参数的。 您将要接受从方法返回的int:

int myResult = Myclass.MyMethod(); 

编辑:除了您的计算方法外,但您似乎知道如何使用它。 现在我不确定您到底是什么问题,因为您在main方法中使用的是OK方法(除非您不是从类名中调用它们,但不必在main方法位于内部的情况下调用它们)类本身)。

由于所有方法都是静态的,因此您可以执行以下操作:

int x1=calling.num1();
int y1=calling.num2();
String s1=calling.operand();
calling.calculation(x1, y1, s1);

但是,如果您没有使它们成为静态的,而是想调用它们,那么您将实例化一个类并在该类中调用方法。

calling app = new calling();
int x1=app.num1();
int y1=app.num2();
String s1=app.operand();
app.calculation(x1, y1, s1);

您有比这更大的问题。 请开始阅读Robert C. Martin的书Clean Code,您的代码不是面向对象的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM