简体   繁体   中英

upper left as well as upper right triangle

I want to insert blank spaces as shown in required output

input string :abc

required output:

abcabc
ab--bc
a----c

But mine comes as:

abcabc
abbc
ac

public static void triangle(String s){

    int length = s.length();

    for(int i=0;i<2*length;i++){
        System.out.println();

        for(int j=0;j<length-i;j++){
            System.out.print(" "+s.charAt(j));
        }                   
        for(int k=i;k<length;k++){
            System.out.print(" "+s.charAt(k));      
        }    
    }
}
    public static void triangle(String s){
    int length = s.length();
    for(int i=0;i<length;i++){
        System.out.println();
        int j=0;
            while(j<length-i){
                System.out.print(s.charAt(j));
                j++;
            }
            while(j<length){
                System.out.print(" ");
                j++;
            }
        int k=0;
        while(k<i){
            System.out.print(" ");
            k++;
        }
        while(k<length){
                System.out.print(s.charAt(k));
                k++;
        }
 }}

Put it under while loops.

Or just for loops :)

for (int i = 0; i < s.length(); i++) {
    for (int j = 0; j < s.length()-i; j++) {
        System.out.print(s.charAt(j));
    }
    for (int j = s.length()-i; j < s.length(); j++) {
        System.out.print(" ");
    }
    for (int j = 0; j < i; j++) {
        System.out.print(" ");
    }
    for (int j = i; j < s.length(); j++) {
        System.out.print(s.charAt(j));

    }
    System.out.println("");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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