0

I am looking for a way to reverse the word in java. This is my code and it occurs errors.

Can somebody explain why?

import java.util.Scanner;

public class Robot {

    public static void reverse(String text) {
        int leng = text.length();
        int i = 0;
        while (leng-i>=0){System.out.print(text.charAt(leng-i));
        i++;
        }
    }

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Type in your text: ");
        String text = reader.nextLine();
        System.out.print("In reverse order: ");
        reverse(text);
    }

}

I expected it to reverse the order of the word but it does not.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
able20
  • 167
  • 1
  • 1
  • 7
  • 3
    always include input, current output and expected output in question. It help in fast debug – SSP Sep 23 '19 at 13:28
  • Remember that the first character is 0, while the last character is at index (length-1), *not* length. – RealSkeptic Sep 23 '19 at 13:29
  • "and it occurs errors" please [edit] your question and add errors to the question, so other people facing them would be able to find this question along and possible answers. – Pshemo Sep 23 '19 at 13:30
  • Possible duplicate of [Reverse a string in Java](https://stackoverflow.com/questions/7569335/reverse-a-string-in-java) – alea Sep 23 '19 at 13:55
  • @alea it's a specific problem, not a general "how to reverse a string" question – Andrew Tobilko Sep 23 '19 at 14:52

2 Answers2

2

It should be

int i = 1;

Otherwise, you will be getting a StringIndexOutOfBoundsException since text.length() is never a valid index.

To make it a bit shorter (and cooler), you might want to write

System.out.print(text.charAt(leng - i++));

Though, we usually do

System.out.print(new StringBuilder(text).reverse());
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
1

Your problem is here:

int leng = text.length();

arrays in java are 0-indexed, which means that the last character in the string is at index (text.length()-1), instead of text.length()

So, you can set leng to text.length()-1, or you can set i to 1

simonalexander2005
  • 4,338
  • 4
  • 48
  • 92