I want to print all letters except the last one, then the last two, then the last 3

Eric Dants :

I'm trying to print a string like this:

cat
ca
c

But with my code now, I'm only getting

ttt
tt
t

code

public static String bingo(String s) {
        int len = s.length();
        for(int i = 1; i <=s.length(); i++) {
            for(int k = 1; k <= s.length() - i+1; k++) {
                System.out.print(s.substring(len-5));
            }
            System.out.println();
        }
        return s;
    }
Alan Sereb :

You almost got it!

This is how it could be done with while loop.

public static String bingo(String s) {

    int index = s.length();
    while (index != 0)
        System.out.println(s.substring(0, index--));

    return s;
}

This is how it could be done with for loop

public static String bingo(String s) {
    for (int i = s.length(); i != 0; i--)
        System.out.println(s.substring(0, i));
    return s;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=311140&siteId=1