Как вывести дефис после каждого символа с ограничениями, используя вложенные циклы for в java - PullRequest
2 голосов
/ 28 мая 2020

У меня только одна небольшая проблема с выводом дефиса после каждого символа (включая три точки, показанные в приведенном ниже коде)

Пример ввода

  2 (option #)
  disappear (phrase)

Ожидаемый результат:

 d-i-s-a-p-p-e-a-r-.-.-.
 d-i-s-a-p-p-e-a-.-.-.
 d-i-s-a-p-p-e-.-.-.
 d-i-s-a-p-p-.-.-.
 d-i-s-a-p-.-.-.
 d-i-s-a-.-.-.
 d-i-s-.-.-.
 d-i-.-.-.
 d-.-.-.
 .-.-.
 .-.
 .

Он выводит «-» после каждого символа, исключая последнюю точку

Я получил «-» для отображения после символа самого слова, но не могу понять, что отображается после точки тоже, вроде работает, но должно быть на один дефис меньше:

Мой фактический результат:

d-i-s-a-p-p-e-a-r-.-.-.-
 d-i-s-a-p-p-e-a-.-.-.-
 d-i-s-a-p-p-e-.-.-.-
 d-i-s-a-p-p-.-.-.-
 d-i-s-a-p-.-.-.-
 d-i-s-a-.-.-.-
 d-i-s-.-.-.-
 d-i-.-.-.-
 d-.-.-.-
 .-.-.-
 .-.-
 .-

Я частично закончил, мне просто нужно на один дефис меньше, автоматически также выполняет требование не отображать дефис после самой последней точки.

Код:

       else if (option == 2){
             for (int x = 0; x < phrase.length(); x++){
                for (int y = 0; y < phrase.length() - x; y++){
                    char n = phrase.charAt(y);
                    System.out.print(n+"-");
                }
                for (int a = 0; a < 3; a++){
                    System.out.print("."+"-");
                }
                System.out.println("");
            }
            for (int j = 0; j < 3; j++){
                for (int i = 0; i < 3 - j; i++){
                    System.out.print("."+"-");
                }
                System.out.println("");
            }
        }

1 Ответ

3 голосов
/ 28 мая 2020

Одним из способов удаления последнего - является печать - только тогда, когда это не последняя итерация . Вы можете проверить, что это не последняя итерация, проверив loopVariable != loopBound - 1.

Итак, ваш код будет:

for (int x = 0; x < phrase.length(); x++){
    for (int y = 0; y < phrase.length() - x; y++){
        char n = phrase.charAt(y);
        System.out.print(n+"-");
    }

    // You could just print the literal "--.-." instead
    for (int a = 0; a < 3; a++){
        System.out.print(".");
        if (a != 2) { // Notice here!
            System.out.print("-");
        }
    }
    System.out.println();
}
for (int j = 0; j < 3; j++){
    for (int i = 0; i < 3 - j; i++){
        System.out.print(".");
        if (i != 2 - j) { // and here
            System.out.print("-");
        }
    }
    System.out.println();
}

Вот как я бы это сделал:

// pretend that the phrase is 3 characters longer than it actually is...
// because of the three dots at the end
for (int x = 0; x < phrase.length() + 3; x++){
    for (int y = 0; y < phrase.length() + 3 - x; y++){
        char n;
        // Should we print the phrase or the dots?
        if (y < phrase.length() - x) {
            n = phrase.charAt(y);
        } else {
            n = '.';
        }
        System.out.print(n);
        if (y != phrase.length() + 2 - x) { // same trick of checking if it is last iteration
            System.out.print("-");
        }
    }
    System.out.println();
}
...