本文介绍了用 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));

        }
    }
}

推荐答案

你在这里:

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));
    }
}

输出:

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"));
}

输出:

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

这篇关于用 Java 写一个菱形/菱形的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 14:14