簡體   English   中英

在另一個類別中存儲價值

[英]Storing value in another class

我創建了兩個類,並且嘗試從“ 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,該值位於下面的“ calculator”類中。

public class Calculator {

    public int firstValue;
    public int secondValue;

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

提前致謝。

Scanner.nextInt() 返回值,您不會將其傳遞給值。 像這樣:

int firstValue = input.nextInt();

對兩個輸入都執行此操作,然后定義值之后,可以將它們傳遞給類的構造函數:

Calculator calculator = new Calculator(firstValue, secondValue);

此外,您應將Calculator類的字段設置為private而不是public 公共領域的形式很差,有很多文獻比我在這里的簡單回答更能解釋這一點。 但是這個想法歸結為一個對象應該完全擁有它的成員,並且僅在需要時才提供對這些成員的訪問(通常是通過Java中的getter / setter方法)。

您可以使用如下代碼:

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實例。

您應該閱讀有關面向對象編程的更多信息,這是一個非常瑣碎的問題。 您可以通過多種方式執行此操作,例如:

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);

或者您可以使用設置器來設置值並使字段私有。 但是正如我之前所說,您應該了解有關OOP的更多信息

nextInt()不接受任何參數!

簡單的只需在計算器中為字段創建吸氣劑和吸氣劑,並在通過掃描儀讀取時進行設置;

要么

另一種方法是在掃描程序讀取時獲取兩個局部變量,並將兩個輸入都存儲在這些局部變量中,然后最終調用計算器的參數化構造函數,並將局部變量作為參數傳遞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM