根据用户输入打印菱形图案

Print a rhombus pattern from user input

我有一个任务要求用户输入(用户名),然后打印出一个菱形图案。 例如: 如果用户名为 Thomas,则输出应如下所示:

T
Th
Tho
Thom
Thoma
Thomas
 homas
  omas
   mas
    as
     s

到目前为止,这是我的代码。我在使用第二个 for 循环时遇到问题。我可以很容易地打印出“Thomas”之前的行,但我不知道如何在前面打印空格,以便单词的末尾位于同一位置。

import java.util.Scanner;

public class wordRhombus {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter your name: ");
    String name = sc.nextLine();
    int enteredNamesLength = name.length();

    for (int i = 0; i <= enteredNamesLength; i++) {
      System.out.println(name.substring(0, (int) i));

      for (int j = 1, k = 1; j <= enteredNamesLength; i++, k++) {
        System.out.println(k * " " + name.substring(j, enteredNamesLength));
      }
    }
  }
}

我认为必须有一个 for 循环来像您所做的那样打印名称,然后是另一个 for space 并在同一个循环中打印子字符串。

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter your name: ");
    String name = sc.nextLine();
    int enteredNamesLength = name.length();

    for (int i = 0; i <= enteredNamesLength; i++) {
            System.out.println(name.substring(0, (int) i));
    }

    for(int i = 1;i <= enteredNamesLength; i++ ) {
            for(int j = 0;j < i; j++) {
                    System.out.print(" ");
            }
            System.out.println(name.substring(i, enteredNamesLength));
    }
}

分两次完成会更容易:substring 从开始到索引,然后打印空格,然后是世界末日,并做一些更改:

  • 无需将 i 转换为 int,它已经是一个 int
  • 第一个循环:开始索引i在1而不是0,不避免空行
  • 第二个循环i的结束索引在enteredNamesLength-1而不是enteredNamesLength以避免空行

for (int i = 1; i <= enteredNamesLength; i++) {    // start at 1
    System.out.println(name.substring(0, i));      // don't cast
}

for (int i = 1; i < enteredNamesLength; i++) {     // stop at enteredNamesLength-1
    for (int space = 0; space <= i; space++) {
        System.out.print(" ");
    }
    System.out.println(name.substring(i, enteredNamesLength));
}

这是另一种解决方案,您可以提取接受startstopprint 方法。如果它们之间有 index,则打印 index 处的字符,否则打印空格。

import java.util.Scanner;

public class wordRhombus {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = sc.nextLine();
        int enteredNamesLength = name.length();

        for (int start = 0, stop = 0; start < enteredNamesLength && stop < enteredNamesLength; ) {
            print(start, stop, name);
            if (stop < enteredNamesLength - 1) {
                stop++;
            } else {
                start++;
            }
        }
    }

    private static void print(int start, int stop, String name) {
        for (int index = 0; index < name.length(); index++) {
            if (index >= start && index <= stop) {
                System.out.print(name.charAt(index));
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}

您可以将上增加部分和下减少部分组合在一个循环中。

Try it online!

public static void main(String[] args) {
    String str = "RHOMBUS";
    int n = str.length();
    // two parts: negative and positive
    for (int i = 1 - n; i < n; i++) {
        // leading whitespaces for the positive part
        for (int j = 0; j < i; j++) System.out.print(" ");
        // negative part: str.substring(0, n + i);
        // positive part: str.substring(i, n);
        String sub = str.substring(Math.max(0, i), Math.min(n + i, n));
        // output the line
        System.out.println(sub);
    }
}

输出:

R
RH
RHO
RHOM
RHOMB
RHOMBU
RHOMBUS
 HOMBUS
  OMBUS
   MBUS
    BUS
     US
      S

另请参阅:

此代码适用于常规 UTF8 字符和代理对

Try it online!

public static void main(String[] args) {
    String str = "";//"RHOMBUS";
    int n = (int) str.codePoints().count();
    // two parts: negative and positive, i.e.
    // upper increasing and lower decreasing
    IntStream.range(1 - n, n)
            // leading whitespaces for the positive part
            .peek(i -> IntStream.range(0, i)
                    .forEach(j -> System.out.print(" ")))
            // negative part: range(0, n + i);
            // positive part: range(i, n);
            .mapToObj(i -> str.codePoints()
                    .skip(Math.max(0, i))
                    .limit(Math.min(n + i, n))
                    .mapToObj(Character::toString)
                    .collect(Collectors.joining()))
            // output the line
            .forEach(System.out::println);
}

输出: