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;
}
}
}
}
There is no null-terminating character in Java strings; they have a
length()method you should use to determine length.Also, the
whileloop would be more idiomatic as:Or as a simple
forloop.