SJ1*_*J19 2 java methods return
在我写一个计算器应用程序时,我无法弄清楚最好的方法是:
private void calculate(String command) {
System.out.print("value1: ");
int value1 = reader.readInteger();
System.out.print("value2: ");
int value2 = reader.readInteger();
if (command.equals("sum"))
System.out.println("sum of the values " + sum(value1 + value2));
}
private int sum(int value1, int value2) {
return value1 + value2;
}
Run Code Online (Sandbox Code Playgroud)
要么
private void calculate(String command) {
System.out.print("value1: ");
int value1 = reader.readInteger();
System.out.print("value2: ");
int value2 = reader.readInteger();
if (command.equals("sum"))
sum();
}
private void sum(int value1, int value2) {
System.out.println("sum of the values " + value1 + value2);
}
Run Code Online (Sandbox Code Playgroud)
第二个calculate()方法使方法更清晰,但通常更喜欢使用返回方法或void(仅用于打印行)?
通常,返回值更好- 然后您可以测试您的方法并在更复杂的计算中重复使用它.
其中一个好方法是定义一些calculate计算和返回值的void show方法,并定义接受作为参数值的方法,以显示在屏幕上并正确显示它.
| 归档时间: |
|
| 查看次数: |
323 次 |
| 最近记录: |