的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