Есть ли способ упростить следующий код. Примерно он настроен на сканирование значения, хотя, если на входе выдается исключение, ему нужно сказать 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\"!");
}
}
}
Извиняюсь за длину, но, надеюсь, я смогу получить примерно половину длины.