我想打印等于行数的asterix - (它们应该从右侧开始)。 它应该从第一行的9个空格和1 *开始,然后是第二行的2 *和8个空格,依此类推,直到第10行应该有10 *和0空格,如下图所示:
我可以在每行打印正确数量的空格,在正确的位置打印1 *。 例如,它在第一行打印9个空格和1 *。 但是在第二行,它在第九个位置打印了8个空格和1 *,而不是两个? 我看不到我在代码中错过了什么:
for (int row = 1; row <= 10; row++) { for (int col = 10; col > row; col--) { System.out.print(" "); if (col <= row) { System.out.print("*"); } } System.out.println("*"); }I want to print asterix which is equals the number of rows - (they should begin from the right side). It should begin with 9 spaces and 1 * at the first line, then 2 * and 8 spaces at the second line and so on until the tenth row which should have 10 * and 0 spaces like the image below:
I can print the right number of spaces at each line and 1 * at the right position. For example it prints 9 spaces and 1 * at the first line. But then at the second line it prints 8 spaces and 1 * at the ninth position instead of two?? I can't see what I have missed in my code:
for (int row = 1; row <= 10; row++) { for (int col = 10; col > row; col--) { System.out.print(" "); if (col <= row) { System.out.print("*"); } } System.out.println("*"); }最满意答案
有几种解决方案:
1)要么为每一行创建两个内部循环:一个写空格,另一个写星
final int rows = 10; for(int row = 1; row <= rows; row++) { for(int i = 0; i < (rows - row); i++) { System.out.print(" "); } for(int i = 0; i < (row); i++) { System.out.print("*"); } System.out.println(); }2)或者您为每一行创建一个内部循环,并检查索引以考虑是否必须打印星号或空格。
final int rows = 10; for(int row = 1; row <= rows; row++) { for(int col = 1; col <= rows; col++) { System.out.print((col <=(rows - row))? " " : "*"); } System.out.println(); }3)或者你可以使用字符串操作与subString (这是丑陋的,但为什么不):
final int rows = 10; final String stars = "************************"; final String blanks = " "; for(int row = 1; row <= rows; row++) { System.out.print(blanks.substring(0, rows - row)); System.out.println(stars.substring(0, row)); }There are several solutions:
1) Either you create two inner loops for each row: one to write the spaces and another to write the stars
final int rows = 10; for(int row = 1; row <= rows; row++) { for(int i = 0; i < (rows - row); i++) { System.out.print(" "); } for(int i = 0; i < (row); i++) { System.out.print("*"); } System.out.println(); }2) Or you create one inner loops for each row and check the index to consider if you have to print a star or a blank.
final int rows = 10; for(int row = 1; row <= rows; row++) { for(int col = 1; col <= rows; col++) { System.out.print((col <=(rows - row))? " " : "*"); } System.out.println(); }3) Or you can use string manipulation with subString (this is ugly but why not):
final int rows = 10; final String stars = "************************"; final String blanks = " "; for(int row = 1; row <= rows; row++) { System.out.print(blanks.substring(0, rows - row)); System.out.println(stars.substring(0, row)); }更多推荐
发布评论