[英]For the following java demo, how would I make it so the methods would not be static?
[英]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.