简体   繁体   中英

Code printing entire string on each line?

I am trying to write code that will take a given word (in this case "Alphabet") and print it backwards. With my current method, I manage to get it to print backwards, however, instead of printing on character per line, it is printing the entire word, starting with the last character on the first print line and then adding the following character on the next.

public class Main {
    public static void main(String[] args) {
        System.out.println();
        System.out.println();
        String backwards = "Alphabet";
        for (int i = backwards.length(); i >= 0; i--) {
            System.out.println(backwards.substring(i));
        }
        System.out.println();
        System.out.println();
    }
}

Change the for loop to start at length() - 1 and use String.charAt(int) instead of String.substring(int) . Like,

for (int i = backwards.length() - 1; i >= 0; i--) {
    System.out.println(backwards.charAt(i));
}

Will change your output to

t
e
b
a
h
p
l
A

surrounded by a bunch of empty lines (which I assume you want).

For the record, you can do something like this too (in one line):

String s = "Alphabet";
new StringBuilder(s).reverse().chars().mapToObj(i -> (char) i).forEach(System.out::println);

If, of course, you are in Java 8+.

If you want yo use the method substring() you can do it as below:

for (int i = backwards.length(); i > 0; i--) {
      System.out.println(backwards.substring(i-1, i));
}

If you want to know how this method works take a look here: substring .

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