Строка, которая повторяется, но не начинается с начала в Java (ромбовидная структура - PullRequest
0 голосов
/ 11 июня 2018

Это работа, которую я проделал до сих пор: я должен напечатать ромбовидный узор, который всегда начинается с верхнего регистра строки, который повторяется, но не всегда начинается с начала.

    public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    String userInput = keyboard.next();
    userInput = Character.toUpperCase(userInput.charAt(0)) + userInput.substring(1);
    int i;
    int j;
    if (userInput.length() % 2 != 0) {

        for(i = 1; i < userInput.length(); i += 2) {
            for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
                System.out.print(" ");
            }

            for(j = 0; j < i; ++j) {
                System.out.print(userInput.charAt(j));
            }

            System.out.println("");
        }

        for(i = userInput.length(); i > 0; i -= 2) {
            for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
                System.out.print(" ");
            }

            for(j = 0; j < i; ++j) {
                System.out.print(userInput.charAt(j));
            }

            System.out.print("\n");
        }
    } else {
        for(i = 2; i < userInput.length(); i += 2) {
            for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
                System.out.print(" ");
            }

            for(j = 0; j < i; ++j) {
                System.out.print(userInput.charAt(j));
            }

            System.out.println("");
        }

        for(i = userInput.length(); i > 0; i -= 2) {
            for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
                System.out.print(" ");
            }

            for(j = 0; j < i; ++j) {
                System.out.print(userInput.charAt(j));
            }

            System.out.print("\n");
        }
    }

}

Например, мойвход "Питер".Таким образом, мой вывод:

  P
 Pet
Peter
 Pet
  P

но это должно быть:

  P
 Ete
Rpete
 Rpe
  T

Я не знаю, что изменить, чтобы сделать эту работу

Ответы [ 3 ]

0 голосов
/ 11 июня 2018

Вам необходимо внести несколько изменений:

  1. Объявить int n=0; после int j;
  2. Всегда печатать userInput.charAt(n++ % userInput.length()) вместо charAt(j)

  3. Чтобы получить только первый символ в строке в верхнем регистре:

    char c = userInput.charAt(n++ % userInput.length());
    c = j == 0 ? Character.toUpperCase(c) : Character.toLowerCase(c);
    System.out.print(c);
    

Проверьте оператор по модулю.

С этими изменениями,вы получите такой вывод:

  P
 Ete
Rpete
 Rpe
  T
0 голосов
/ 11 июня 2018

Вот сокращенная версия вашего кода:

public static void main(String[] args) {
    String userInput = "Peter";
    int length = userInput.length();
    int m, j, i, n = 0;
    for (m = length % 2 > 0 ? 1 : 2; m < length * 2; m += 2) {
        i = m < length ? m : length * 2 - m;
        for (j = 0; j < length - 1 - i / 2; ++j) {
            System.out.print(" ");
        }

        for(j = 0; j < i; ++j) {
            char c = userInput.charAt(n++ % length);
            c = j == 0 ? Character.toUpperCase(c) : Character.toLowerCase(c);
            System.out.print(c);
        }

        System.out.println("");
    }
}
0 голосов
/ 11 июня 2018

Учитывая тот факт, что сам ввод печатается циклически, мы можем использовать его.Мое предложение состоит в том, чтобы объединить входную строку и распечатать подстроки, которые определяются структурой ромбовидного узора.

public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        String userInput = keyboard.next();
        String concatenated = userInput;

        // build up the index array
        int i, cumSum = 0;
        ArrayList<Integer> helperIndex = new ArrayList<>();
        for(i = 1; i < userInput.length(); i += 2) {
            helperIndex.add(i);
            cumSum += i;
        }
        for(i = userInput.length(); i > 0; i -= 2) {
            helperIndex.add(i);
            cumSum += i;
        }
        int numOfWordRepitition = cumSum / userInput.length() ;
        for (i = 0; i < numOfWordRepitition; i++){
            concatenated += userInput;
        }

        // print out diamond
        String substr;
        int prev = helperIndex.get(0);
        int next = helperIndex.get(0);
        substr = concatenated.substring(0 , helperIndex.get(0));
        System.out.println(Character.toUpperCase(substr.charAt(0)) + substr.substring(1));
        for(i = 1; i < userInput.length(); i++){
            next += helperIndex.get(i);
            substr = concatenated.substring(prev , next);
            substr = Character.toUpperCase(substr.charAt(0)) + substr.substring(1);
            System.out.println(substr);
            prev = next;
        }

    }
...