简体   繁体   English

用 Java 写一个菱形/菱形的单词

[英]Writing a word in a rhombus/diamond shape in Java

I have to write a program that asks a word and then prints it in a rhombus/diamond shape, like this:我必须编写一个程序,询问一个单词,然后将其打印为菱形/菱形,如下所示:

Word: Hello
H
He
Hel
Hell
Hello
 ello
  llo
   lo
    o

I tried something but I really could use some help if someone could, I tried something like this:我尝试了一些东西,但如果有人可以的话,我真的可以使用一些帮助,我尝试过这样的事情:

import java.util.Scanner;

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

        System.out.print("Word: ");
        String word = sc.nextLine();
        int wordLength = word.length();

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

        }
    }
}

Here you are:这个给你:

public static void main(String[] args) {
    printRhombusText("yolobird");
}

public static void printRhombusText(String s) {
    // top part
    for (int i = 1; i <= s.length(); ++i) {
        System.out.println(s.substring(0, i));
    }
    // bottom part
    for (int i = 1; i <= s.length(); ++i) {
        // print out the space
        for (int y = i; y > 0; --y) {
            System.out.print(" ");
        }
        System.out.println(s.substring(i));
    }
}

output:输出:

y
yo
yol
yolo
yolob
yolobi
yolobir
yolobird
 olobird
  lobird
   obird
    bird
     ird
      rd
       d
        

Want to add user input?想要添加用户输入? Here:这里:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    do {
        System.out.print("Input your text: ");
        String input = scanner.nextLine();
        printRhombusText(input);
        scanner.reset();
        System.out.print("You want to do one more? (y/n): ");
    } while (scanner.nextLine().trim().equals("y"));
}

output:输出:

Input your text: kiet
k
ki
kie
kiet
 iet
  et
   t
    
You want to do one more? (y/n): y
Input your text: ahihi
a
ah
ahi
ahih
ahihi
 hihi
  ihi
   hi
    i
     
You want to do one more? (y/n): n

You can use this code to output a word in a rhombus shape.您可以使用此代码以菱形输出单词。

Try it online! 在线试试吧!

public static void main(String[] args) {
    String str = "RhOmBuS";
    int h = str.length();
    // two parts: negative and positive, i.e.
    // upper increasing and lower decreasing
    for (int i = 1 - h; i < h; i++) {
        // white space padding for the positive part
        for (int j = 0; j < i; j++) System.out.print(" ");
        // negative part: str.substring(0, h + i);
        // positive part: str.substring(i, h);
        String sub = str.substring(Math.max(0, i), Math.min(h, h + i));
        // output the line
        System.out.println(sub);
    }
}

Output:输出:

R
Rh
RhO
RhOm
RhOmB
RhOmBu
RhOmBuS
 hOmBuS
  OmBuS
   mBuS
    BuS
     uS
      S

See also: Print a rhombus pattern from user input另请参阅:根据用户输入打印菱形图案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM