我是 Java 编程新手。 最近我在做Java作业。 我在用户定义的类中缝制了这个方法
public void intputRank( Scanner s) {
salary = s.nextInt();
}
我很困惑,因为我总是想把 I/O 放在 main
方法中(就像在 C++ 中一样,我只在 main 函数中写 cin
cout
)。我这样做有两个原因:
- 我可以很容易地看到我的程序在哪里接受
输入
。当 I/O 出现问题时,我只需要调试main
方法即可。 - Scanner是一个比较复杂的
类
,用它作为参数会导致unknown错误。
那么,善良的 Stack Overflowers,这只是一个不好的例子还是我理解错误了?
如果是后者呢?为什么不呢
public void inputRank( int asalary) {
salary = asalary;
}
//in main method
Scanner reader = new Scanner(System.in);
int asalary = reader.nextInt();
//then pass the asalary as parameter
最佳答案
如果您的程序需要健壮,例如当提示输入整数时,它会验证输入并在错误时重新提示,那么拥有可重用的辅助方法是一件好事。
这意味着您将需要多种使用 Scanner
的方法。现在,您可以将 Scanner
对象作为参数传递,也可以将其放入字段中,这完全取决于您。
但要点是,在使用 Scanner
的方法中包含代码是完全可以的,而且它确实是健壮代码所必需的,否则您将毁掉 DRY (不要重复自己)原则。
示例:
public static int promptNonNegativeInt(Scanner sc, String prompt) {
for (;;) {
System.out.print(prompt + ": ");
if (! sc.hasNextInt()) {
System.out.println("** Not a valid number, please try again");
sc.nextLine(); // discard bad input
continue;
}
int value = sc.nextInt();
sc.nextLine(); // discard any extra text on the line
if (value < 0) {
System.out.println("** Number cannot be negative, please try again");
continue;
}
return value;
}
}
使用示例
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int value = promptNonNegativeInt(sc, "Enter number");
System.out.println("You entered: " + value);
}
更复杂的是,如果您需要提示输入具有多个字段的对象。隔离执行此操作的代码是良好的编程(关注点分离),因此编写 promptMyObject(Scanner sc)
方法是一件好事。
特别是当您需要提示输入各种对象时。如果将所有提示代码留在 main()
方法中,那么它将变得巨大且难以阅读。这将是 God method , God object 的变体:
A God object is an object that knows too much or does too much. The God object is an example of an anti-pattern.
关于Java 可以只将输入/输出放在主方法中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49891340/