2016-12-27 48 views
0

我創建了兩個類,我試圖從UserInterface類中的用戶獲取值,但我希望它存儲在我的第二個類「Calculator」中。在另一個類中存儲值

import java.util.Scanner; 

public class UserInterface { 

    public static void main (String Args[]) { 
     Calculator calculator = new Calculator(); 
     Scanner input = new Scanner(System.in); 
     System.out.println("Enter your first value: \t"); 
     input.nextInt(firstValue); 
     System.out.println("Enter your second value: \t"); 
     input.nextInt(secondValue); 
    } 
} 

我想input.nextInt(firstValue);將值傳遞給下面顯示的「計算器」類中的firstValue。

public class Calculator { 

    public int firstValue; 
    public int secondValue; 

    public Calculator(int firstValue, int secondValue) { 
     this.firstValue = firstValue; 
     this.secondValue = secondValue;   
    } 
} 

在此先感謝。

+1

此代碼不會編譯。除非你沒有向我們展示空的構造函數。 –

+0

'計算器。firstValue'是'public'。什麼阻止你直接存儲它? –

+0

OP,請在這裏發佈問題之前閱讀基本的Java教程。 –

回答

3

您可以使用這樣的代碼:

public static void main (String Args[]) { 
    Calculator calculator = new Calculator(); 
    Scanner input = new Scanner(System.in); 
    System.out.println("Enter your first value: \t"); 
    calculator.firstValue = input.nextInt(); 
    System.out.println("Enter your second value: \t"); 
    calculator.secondValue = input.nextInt(); 
} 

或代碼:

public static void main (String Args[]) { 
    Scanner input = new Scanner(System.in); 
    System.out.println("Enter your first value: \t"); 
    int firstValue = input.nextInt(); 
    System.out.println("Enter your second value: \t"); 
    int secondValue = input.nextInt(); 
    Calculator calculator = new Calculator(firstValue, secondValue); 
} 

在第一個例子,一個calculator實例被創建後要設置的值。

在第二個,您正在創建具有所需值的calculator實例。

+1

'nextInt'不帶參數。也請添加幾句話解釋。 –

5

Scanner.nextInt()返回的值,你不要傳遞它的值。事情是這樣的:

int firstValue = input.nextInt(); 

這樣做對您的兩個輸入,然後後你定義的值,你可以將它們傳遞到構造函數類:

Calculator calculator = new Calculator(firstValue, secondValue); 

另外,您應該使Calculatorprivate而不是public的字段。公共領域的形式很差,並且有很多文獻可以解釋它比我在這裏簡單的回答更好。但是這個想法歸結爲一個對象應該完全擁有它的成員,並且只有在需要時才提供對這些成員的訪問(通常通過Java中的getter/setter)。

2

你應該閱讀更多關於面向對象編程的知識,這是非常微不足道的問題。你可以在很多方式,例如做到這一點:

System.out.println("Enter your first value: \t"); 
int value = input.nextInt(); 
calculator.firstValue = value; 

Scanner input = new Scanner(System.in); 
System.out.println("Enter your first value: \t"); 
int firstValue = input.nextInt(); 
System.out.println("Enter your second value: \t"); 
int secondValue = input.nextInt(); 
Calculator calculator = new Calculator(firstValue, secondValue); 

,或者您可以使用setter方法來設置值,使私人領域。但正如我之前所說,你應該瞭解更多關於OOP

0

nextInt()不帶任何參數!

簡單隻需在計算器中爲字段創建getter和setter,並在讀取掃描器時設置它們;

OR

另一種方法是取兩個局部變量由掃描儀讀取,同時和兩個輸入這些局部變量存儲,然後最後調用計算器的參數的構造函數傳遞局部變量作爲自變量。

相關問題