有什么方法可以简化以下代码。粗略设置的方式是扫描值,但是如果输入引发异常,则需要说出nonono并重新搜索该值。我需要像这样收集x和y值,然后才能以科学的计算器方式对其进行操作。输入字符串“ RESULT” =先前计算的答案是必要条件。这两个要求x和y的循环是如此相似,只有“第一个操作数”和“ x =答案”,而“第二个操作数”和“ y =答案”不同。那么,有什么方法可以优化此代码,以便仅需一个循环,因为两者是如此相似?这是代码。
String operand;
double x = 0;
double y = 0;
//These two arrays are the differences between both of the loops that follow. Everything besides first, x and second, y are the same
String arr[] = {"first", "second"};
Double var[] = {x, y};
boolean operandLoop1 = false;
//x
while (!operandLoop1) {
System.out.print("Enter " + arr[0] + " operand: ");
operand = calcOption.next(); // retrieve first value
if (operand.equals("RESULT")) {
var[0] = answer; // If I want to use the previous result as my input
operandLoop1 = true;
} else {
try {
var[0] = Double.parseDouble(operand); // Assumes that if it isn't RESULT, then I'll want to put in a number
operandLoop1 = true;
} catch (NumberFormatException nfe) { // necessary if I type anything else in besides RESULT and a double
System.out.print("Error: Invalid input! Correct inputs are any real number and \"RESULT\"!");
}
}
}
boolean operandLoop2 = false;
//y
while (!operandLoop2) {
System.out.print("Enter" + arr[1] + " operand: ");
operand = calcOption.next(); // retrieve second value
if (operand.equals("RESULT")) {
var[1] = answer; // If I want to use the previous result as my input
operandLoop2 = true;
} else {
try {
var[1] = Double.parseDouble(operand); // Assumes that if it isn't RESULT, then I'll want to put in a number
operandLoop2 = true;
} catch (NumberFormatException nfe) { // necessary if I type anything else in besides RESULT and a double
System.out.print("Error: Invalid input! Correct inputs are any real number and \"RESULT\"!");
}
}
}
很抱歉,但希望我能将其长度缩短一半。
答案 0 :(得分:0)
由于这两个部分之间唯一的区别是数组索引,因此可以使用如下所示的for循环:
for (int i = 0; i < 2; i++) {
boolean operandLoop = false;
while (!operandLoop) {
System.out.print("Enter " + arr[i] + " operand: ");
operand = calcOption.next(); // retrieve value
if (operand.equals("RESULT")) {
var[i] = answer; // If I want to use the previous result as my input
operandLoop = true;
} else {
try {
var[i] = Double.parseDouble(operand); // Assumes that if it isn't RESULT, then I'll want to put in a number
operandLoop = true;
} catch (NumberFormatException nfe) { // necessary if I type anything else in besides RESULT and a double
System.out.print("Error: Invalid input! Correct inputs are any real number and \"RESULT\"!");
}
}
}
}
您还可以使其成为一种方法,传入calcOption
,answer
和序数(arr[0]
)的参数,并替换{{1}的所有赋值}和return语句。我不知道var[0]
的类型,但是看起来像这样:
calcOption