Проверка и использование двух массивов в циклах - PullRequest
0 голосов
/ 17 сентября 2018

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

Извиняюсь за длину, но, надеюсь, я смогу получить примерно половину длины.

1 Ответ

0 голосов
/ 17 сентября 2018

Поскольку единственное различие между двумя разделами - это индекс массива, вы можете использовать цикл 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]), и заменив все присваивания для var[0] операторами возврата. Я не знаю тип calcOption, но это будет выглядеть примерно так:

Double methodName(Object calcOption, Double answer, String ordinal) {
    boolean operandLoop = false;
    while (!operandLoop) {
        System.out.print("Enter " + ordinal + " operand: ");
        String operand = calcOption.next(); // retrieve value
        if (operand.equals("RESULT")) {
            return answer; // If I want to use the previous result as my input
        } else {
            try {
                return Double.parseDouble(operand); // Assumes that if it isn't RESULT, then I'll want to put in a number
            } catch (NumberFormatException nfe) { // necessary if I type anything else in besides RESULT and a double
                throw new RuntimeException("Error: Invalid input! Correct inputs are any real number and \"RESULT\"!");
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...