1

I am just a beginner and do not know how to reverse text that I write on input so it is reversed on output. I wrote something like this:

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        String[] pole = {s};
        for (int i = pole.length; i >= 0; i--) {
            System.out.print(pole[i]);
        } // TODO code application logic here
    }
}

but it is not working and I cannot figure out why.

kryger
  • 12,906
  • 8
  • 44
  • 65
Ales
  • 11
  • 1

1 Answers1

1

Welcome to SO and java world. As I understand the problem is not only reversing a String. The problem is also you do not know about Strings and arrays.

Let's see your code line by line;

 public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Read a String
        String s = sc.nextLine();
        // Put String into an array
        String[] pole = { s };
        // pole's length is 1, because pole has only one String
        for (int i = pole.length; i > 0; i--) {
            // pole[i-1] is the input String
            // System.out.print(pole[i]); // pole[i] get java.lang.ArrayIndexOutOfBoundsException
            System.out.print(pole[i - 1]); // this will print input string not reverse

        }

        // To iterate over a String
        for (int i = s.length() - 1; i >= 0; i--) { // iterate over String chars
            System.out.print(s.charAt(i)); //this will print reverse String.
        }
    }

Also as given on comments, Java have ready methods to reverse a String. Like;

new StringBuilder(s).reverse().toString()
Yusuf K.
  • 4,195
  • 1
  • 33
  • 69