【发布时间】:2017-03-11 22:22:00
【问题描述】:
今天我正在重构我的一个旧 Java 练习。
这是一个简单的加法程序,要求用户输入一些数字,然后返回所有输入数字的总和。
package methodparametertest;
import java.util.Scanner;
public class MethodParameterTest {
public static double adds(double a, double b, double c, double d, double e,
double f, double g) {
double sum = a + b + c + d + e + f + g;
return sum;
}
public static double getDoubleInput(String valueWanted) {
Scanner input = new Scanner(System.in);
String askFor = valueWanted;
System.out.println("Please enter a positive integer or decimal value"
+ "for your numnber of "+askFor);
double valueGiven = input.nextDouble();
return valueGiven;
}
public static void main(String[] args) {
double a = getDoubleInput("passengers");
double b = getDoubleInput("odometer_miles");
double c = getDoubleInput("fuel_gallons");
double d = getDoubleInput("miles_per_gallon");
double e = getDoubleInput("seats");
double f = getDoubleInput("wheels");
double g = getDoubleInput("lights");
System.out.println("Your total number of things: " +adds(a,b,c,d,e,f,g));
}
}
过去,我程序的大部分逻辑都在我的 main 方法中。我今天的目标是尽可能少行 可能在 main 中,并将尽可能多的逻辑打包到单独的方法中。
main 中仍有几行使用我的 getDoubleInput 方法设置变量 a 到 g 的值(然后将用作我的“adds”方法的参数。
我想更改此块并使用循环。也许会像这样工作:
#Shell-like pseudocode
For i in (a b c d e f g)
For j in ("passengers", "odometer miles", "fuel gallons", "miles_per_gallon", "seats", "wheels", "lights");
do
double $i = getDoubleInput($j);
done
//OUTPUT
// double a = getDoubleInput("passengers");
// double b = getDoubleInput("odometer miles");
// double c = getDoubleInput("fuel gallons");
// double d = getDoubleInput("miles_per_gallon");
// double e = getDoubleInput("seats");
// double f = getDoubleInput("wheels");
// double g = getDoubleInput("lights");
但是,我找不到如何在 java 中实现此功能的示例。我见过的大多数循环只迭代数值,而不是一组定义的字符串。
有谁知道循环结构可以 A:遍历字符串,B:使用两个变量?
【问题讨论】:
标签: java for-loop multiple-value