的BAD和避免同時LEARNING解決方案:移動age
和math
局部變量在類static
領域。
的類將是這樣的:
public class TestScanner {
static int age;
static int math;
//rest of your class...
//in method grabInput
static void grabInput() {
//comment the variables
//int age, math;
}
}
上面的代碼將工作,由於static
領域的使用。首先了解what static
means和be careful when using it。
你應該問自己以下問題:
- 我應該有顯示同一類中的
TestScanner
領域的方法?
- 我應該創建一個新的
TestScanner
實例來顯示另一個TestScanner
實例的值嗎?
如果您對兩個問題都回答「是」,那麼您可以創建一個方法來接收TestScanner
的實例並打印其內容。這是你的類將如何看起來像:
public class TestScanner {
//Note: they're not static anymore (yay!)
int age;
int math;
public static void main (String args[]) {
TestScanner disInput = new TestScanner();
TestScanner gInput = new TestScanner();
gInput.grabInput();
//note that now we need to pass the instance of TestScanner
//in order to print its contents
disInput.displayInput(gInput);
}
//method for display purposes
void displayInput(TestScanner testScanner) {
System.out.println("Scanner Input here: ");
System.out.println("What is my age: ");
System.out.println(testScanner.age);
System.out.println("What is 2 +2: ");
System.out.println(testScanner.math);
}
void grabInput() {
Scanner stdin = new Scanner(System.in);
System.out.println("What is my age: ");
this.age = stdin.nextInt();
System.out.println("What is 2 +2: ");
this.math = stdin.nextInt();
}
}
現在問自己:我需要這一切?這是一個很好的設計嗎?我是否可以輕鬆執行更改,或者是否需要更多時間和精力來添加新變量,填充並顯示它?
這裏主要的問題叫做cohesion。這是一個班級的功能程度。正如你所看到的,TestScanner
本身有許多責任:
- 商店
age
和math
- 從用戶輸入讀吧
- 顯示的數據傳送給用戶
更好的方法將是在兩類分離這些功能:
Person
(或其他名稱)將存儲來自用戶輸入的數據。基於age
和math
字段的名稱,我想這個類的一個適當的名稱可能是Person
。這門課將負責存儲數據並提供不同的用途,例如存儲用戶輸入,然後將其用於顯示目的。
- 甲
TestScanner
類,其中將測試的Scanner
使用以從用戶輸入和顯示數據中的數據讀出到用戶。
的設計看起來就像這樣:
class Person {
private int age;
private int math;
public Person(int age, int math) {
this.age = age;
this.math = math;
}
public int getAge() {
return this.age;
}
public int getMath() {
return this.math;
}
//setters avoided for this case
}
class TestScanner {
Scanner scanner;
public TestScanner(Scanner scanner) {
this.scanner = scanner;
}
public Person grabInput() {
System.out.println("What is my age: ");
int age = stdin.nextInt();
System.out.println("What is 2 +2: ");
int math = stdin.nextInt();
return new Person(age, math);
}
public void displayInput(Person person) {
System.out.print("My age: ");
System.out.println(person.getAge());
System.out.print("My value of 2 +2: ");
System.out.println(person.getMath());
}
public static void main(String[] args) {
TestScanner testScanner = new TestScanner(new Scanner(System.in));
Person person = testScanner.grabInput();
testScanner.displayInput(person);
}
}
注意:問題而提供的鏈接是不是用來裝飾的目的。
檢查[將信息傳遞給方法或構造函數](https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html)。另外,檢查[爲什麼靜態變量被認爲是邪惡的?](http://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil)如果有人發佈一個答案,使用靜態 – sam
@sam有人回答使用'static'爲*解決方案* –
@LuiggiMendoza好了,我的努力張貼鏈接已見成效:)使用'static'領域的解決方案 – sam