java asterisk right triangle

前端 未结 5 1223
星月不相逢
星月不相逢 2020-12-11 11:56

I\'d like to try a right triangle asterisk. But I only got this output: (I can\'t place here the asterisk)

@ 
@@
@@@

what

相关标签:
5条回答
  • 2020-12-11 12:34

    Try This :

    public class PrintPyramidStar {  
    
       public static void main(String args[]) {  
    
        int c = 1;  
        for (int i = 1; i <= 5; i++) {  
            for (int j = i; j < 5; j++) {  
                System.out.print(" ");
            }  
            for (int k = 1; k <= c; k++) {  
                if (k % 2 == 0)  
                    System.out.print(" ");  
                else  
                    System.out.print("*");  
            }  
            System.out.println();  
            c += 2;  
        }  
      }  
    }  
    
    0 讨论(0)
  • 2020-12-11 12:49

    Try the following:

    import java.io.*;
    public class Star2 {
    
        public static void main(String[] args)throws IOException {
    
            InputStreamReader read = new InputStreamReader(System.in);
            BufferedReader in = new BufferedReader(read);
            int i,j,n=0,k;
            System.out.print("How many stars you want to print in first row ? ");
            n=Integer.parseInt(in.readLine());
            for (i = 0; i<n; i=i+2)
            {
                for (j=i; j<n;j++)
                System.out.print ("*");
                System.out.println();
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-12-11 12:58
    for(int i = 0; i < 9; i++) {
        for(int j = 9; j > 0; j--)
            System.out.print(i < j ? " " : "*");
    
        System.out.println();
    }
    
    0 讨论(0)
  • 2020-12-11 12:59

    Your code never prints any spaces, that should be a problem.

    You can use this simple approach:

    for (int i = 0; i < 3; i++) System.out.println("  @@@".substring(i, i+3));
    

    The logic is quite simple: you have the string with two spaces and three at-signs. The first line of output needs to be two spaces and a single at-sign, so that's the first three chars of the string. The second line should be one space and two at-signs—that's the three chars of the string after skipping the first one; and so on: you just slide through the string, each time skipping one more from the beginning and taking the next three chars.

    Demo

    0 讨论(0)
  • 2020-12-11 13:01

    Your problem is that you are not outputting any white space. Calculate how much whitespace you need to offset each line first, output this white space then output your *'s

    0 讨论(0)
提交回复
热议问题