简体   繁体   English

Java - 如何创建交替三角形金字塔?

[英]Java - How to create alternating triangle pyramid?

I am trying to create a triangle pyramid of alternating "*" and "o" characters, with the number of rows being based on user input.我正在尝试创建一个交替的“*”和“o”字符的三角形金字塔,行数基于用户输入。 The expected output I am trying to achieve, if the user inputs "6" for the number of rows, is:如果用户输入“6”作为行数,我试图实现的预期输出是:

      *
     *o*
    *o*o*
   *o*o*o*
  *o*o*o*o*
 *o*o*o*o*o*

The code I have written to achieve this is:我为实现这一目标而编写的代码是:

String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
    for (int j = 0; j < rows-i; j++){
        System.out.print(star);
    }
    for (int k = 0; k <= i; k++){
        System.out.print(circle);
    }
    System.out.println();
}

However, the output from my code does not match the pyramid above.但是,我的代码的输出与上面的金字塔不匹配。 The output of my code, with a user input of "6", is:我的代码的输出(用户输入为“6”)是:

******o
*****oo
****ooo
***oooo
**ooooo
*oooooo

After spending the last three hours scouring both this website and others, I have still come up lost on how to alternate the characters, how to have the correct number of characters in each row, and how to format the pyramid as the expected output is.在花了最后三个小时搜索这个网站和其他网站之后,我仍然迷失在如何交替字符、如何在每行中有正确的字符数以及如何按照预期输出格式化金字塔。 I don't know if my code is completely wrong, or if I am only missing a part to make it work correctly, but any advice or references is greatly appreciated.我不知道我的代码是否完全错误,或者我是否只是遗漏了一部分以使其正常工作,但非常感谢任何建议或参考。

You could approach it another, far simpler, way.你可以用另一种更简单的方式来处理它。

In pseudo code:在伪代码中:

  • create a String of n spaces创建一个包含n空格的字符串
  • add "*" to it给它加上"*"
  • loop n times, each iteration of the loop:循环n次,循环的每次迭代:
    • print it打印出来
    • replace " *" with "*O*"" *"替换为"*O*"

This recognises a simple way to create the first line, and a simple way to create the next line from the previous line.这识别了一种创建第一行的简单方法,以及一种从上一行创建下一行的简单方法。 Each replacement will match only the last (leading) space and the first star, replacing the space with a star, the star with an O and adding a star.每次替换将仅匹配最后一个(前导)空格和第一颗星,用星替换空格,用 O 替换星并添加星。

Usually the best way to solve a hard problem is to look at it in a way that makes it a simple problem (or a collection of simple problems).通常,解决难题的最佳方法是以使其成为简单问题(或一组简单问题)的方式来看待它。


A couple of ways to create a String of n spaces:创建一个包含n空格的 String 的几种方法:

  • A loop that adds ' ' each iteration每次迭代都添加' '循环
  • new String(new char[n]).replace('\\0', ' ')

How to replace certain characters of a String with other characters:如何用其他字符替换字符串的某些字符:

str = str.replace(" *", "*O*");

This method will work fine:这种方法可以正常工作:

public void printPyramid (int input) {
    for (int row = 1; row <= input; row++) {
        for (int whitespace = input - 1; whitespace >= row; whitespace--) {
            System.out.print(" ");
        }
        System.out.print("*");
        for (int circle = 1; circle < row; circle++) {
            System.out.print("o*");
        }
        System.out.println();
    }
}
                         *
                        *o*
                       *o*o*
                      *o*o*o*
                     *o*o*o*o*
                    *o*o*o*o*o*
                   *o*o*o*o*o*o*
                  *o*o*o*o*o*o*o*
                 *o*o*o*o*o*o*o*o*
                *o*o*o*o*o*o*o*o*o*
               *o*o*o*o*o*o*o*o*o*o*
              *o*o*o*o*o*o*o*o*o*o*o*
             *o*o*o*o*o*o*o*o*o*o*o*o*
            *o*o*o*o*o*o*o*o*o*o*o*o*o*
           *o*o*o*o*o*o*o*o*o*o*o*o*o*o*
          *o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
         *o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
        *o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
       *o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
      *o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
     *o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*

Welcome to Stack Overflow!欢迎使用堆栈溢出! First, the "o"s and "*"s are not alternating because the for loops execute until completion.首先,"o" 和 "*" 不会交替,因为 for 循环会执行直到完成。 This means the stars and circles will print out separately.这意味着星星和圆圈将分别打印出来。 For this application you only need one for loop and two if statements based on whether the "i" in the for loop is odd or even.对于这个应用程序,根据 for 循环中的“i”是奇数还是偶数,您只需要一个 for 循环和两个 if 语句。 An easy way to do this is with the modulo function :一个简单的方法是使用模函数:

String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
    if ((i % 2) == 0)
    {
        System.out.print(circle);
    }
    else
    {
        system.out.print(star);
    }
 System.out.println();
}

See if that works.看看这是否有效。 Thanks!谢谢!

Here is a solution, easy to understand and friendly for beginners.这是一个解决方案,易于理解,对初学者友好。
(If you want to go more advanced, look at the solution from @Bohemian♦ ) (如果你想更高级,看看@Bohemian♦ 的解决方案)

String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
    // How many "o" do we need?
    int count_circle = i;

    // How many * do we need?
    int count_star = count_circle + 1;

    // Let's create the string with o and *
    String output = "";
    for(int j = 0; j < (count_circle + count_star); j++){
        if(j % 2 == 0) // if it is odd
            output = output + star;
        else // if it is even
            output = output + circle;
    }

    // Do we need spaces at the beginning?
    String spaces = "";
    for(int j = 0; j < rows - i - 1; j++){
        spaces = spaces + " ";
    }

    // Final output
    output = spaces + output;
    System.out.println(output);
}

Try this.尝试这个。

Scanner in = new Scanner(System.in);
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; ++i) {
    System.out.printf("%" + (rows - i) + "s", "*");
    for (int j = 0; j < i; ++j)
        System.out.print("o*");
    System.out.println();
}

Ex: If rows=3例如:如果行=3

*## *##

**# **#

*** ***

class Main{
public static void main(String x[]){
    Scanner scan=new Scanner(System.in);
    int rows=scan.nextInt();
    for(int i=1;i<rows;i++){
        for (int j=0;j<i;j++)
        {
        System.out.print("*");
        }
    for (int j=rows;j>i;j--)
        {
        System.out.print("#");
        }
    System.out.println();
    }
}
}

See if that works.看看这是否有效。 Thanks!谢谢!

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

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