Reputation: 331
I have written a short String reverse program in C++. I decided to write it in Java, and so I did. However, once I completed writing the program, I encountered several errors that I have tried to fix but cannot fix. One of the errors was an ArrayOutOfBounds exception. Please help me fix the errors. The C++ program worked fine. Below is the Java code. Please note that I do not want to use inbuilt functions.
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String word;
int i = 0;
boolean inp = true;
System.out.println("Enter one or more words to be reversed:");
word = scan.nextLine();
char wordArray[] = word.toCharArray();
while(wordArray[i]!='\0')
i++;
while(inp == true){
i--;
System.out.println(wordArray[i]);
if(i==0){
System.out.println();
break;
}
}
}
}
Upvotes: 0
Views: 5827
Reputation: 236140
This is another possibility, perhaps simpler:
public String reverse(String str) {
char[] chars = str.toCharArray();
int n = chars.length;
for (int i = 0; i < n/2; i++) {
char tmp = chars[i];
chars[i] = chars[n-i-1];
chars[n-i-1] = tmp;
}
return new String(chars);
}
And although you mentioned that you don't want to use built-in functions, the most idiomatic way would be this:
public String reverse(String str) {
return new StringBuilder(str).reverse().toString();
}
Upvotes: 3
Reputation: 9455
Java Strings are not zero-terminated, thus the byte array created from string isn't either. You used a loop to determine the length of your array, but that loop doesn't find a byte with value 0, so it goes over the range. Use word.length()
instead.
The second thing: You used System.out.println
to print the character - that inserts a linebreak after each character. Is this intended?
Upvotes: 0
Reputation: 8147
strings in java are not necessarily null terminated, you should use String.length() method to find out how long it is.
Upvotes: 0
Reputation: 160311
There is no null-terminating character in Java strings; they have a length()
method you should use to determine length.
Also, the while
loop would be more idiomatic as:
while (true) {
...
}
Or as a simple for
loop.
Upvotes: 8