从用户输入打印菱形图案 [英] Print a rhombus pattern from user input

查看:68
本文介绍了从用户输入打印菱形图案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项任务要求用户输入(用户名),然后从中打印出菱形图案.例如:如果用户的名字是 Thomas,那么输出应该是这样的:

I have a task to ask user for input (user's name) and then to print a rhombus pattern out of it. For example: If user's name is Thomas, then the output should be like this:

T
Th
Tho
Thom
Thoma
Thomas
 homas
  omas
   mas
    as
     s

这是我目前的代码.我在使用第二个 for 循环时遇到问题.我可以轻松地打印出Thomas"之前的行,但我不知道如何在前面打印空格以使单词的结尾在同一位置.

This is my code so far. I am having trouble with second for loop. I can easily print out lines until "Thomas", but I don't know, how to print whitespace infront so that the end of the word will be on the same place.

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 循环来像您所做的那样打印名称,然后另一个用于空间并在相同的内部打印子字符串.

I think there must be one for loop to print the name like what you did, then another for space and inside the same print the substring.

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

这篇关于从用户输入打印菱形图案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆