這個問題對許多人來說似乎很愚蠢,但我似乎缺乏對Java的一些基本理解。我從來沒有在一個項目中使用過幾個類。 對於一個更大的項目,我想將代碼拆分爲幾個類,它們必須相互操作。 這是一個更好理解的基本例子。Java:如何在另一個類中使用一個類的對象
我有三個類TestMain,TestA和TestB。 TestMain讀入兩個字符串input1和input2。 TestA將input1解析爲int inputA,TestB將input2解析爲int inputB。 TestA然後使用inputA和inputB生成result1,並且TestB使用result1創建result2。 之後,TestMain打印出兩個結果。
我不確定這是否可能,因爲類必須同時互相交互。由於這是我的其他項目所必需的,這是我的第一個問題 - 這甚至有可能嗎?
我的代碼到現在爲止是這樣的,但有幾個問題是:
public class TestMain {
public static void main(String[] args) throws IOException {
String input1, input2;
TestA testA = new TestA(); TestB testB = new TestB();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
input1 = br.readLine();
input2 = br.readLine();
System.out.println("A: " + testA.result1 + ", B: " + testB.result2);
}
}
public class TestA {
public static void main(String args[]){
String inputA;
int a; int result;
TestMain testMain = new TestMain(); TestB testB = new TestB();
inputA = testMain.input1;
a = Integer.parseInt(inputA);
result1 = a*testB.b;
}
}
public class TestB {
public void main(String args[]){
String inputB;
int b;
int result2;
TestMain testMain = new testMain(); TestA testA = new testA();
inputB = testMain.input1;
b = Integer.parseInt(inputB);
result2 = testA.result1*2;
}
}
那我解決不了這個非常簡單的例子顯示我缺乏基礎的,所以我希望你能幫助我。 乾杯,Joshflux
謝謝,我會研究它:)。 – Joshflux