+ 1
Can someone help me with a java program that takes input from user and print the reverse of the imput
Can someone help me with a java program that takes input from user and print the reverse of the imput
11 Answers
+ 3
Did you try? Do share it with us if you did or else first give it an attempt and let us know where you are struck.
+ 2
Which statements?
For string, I added in comments. For any variable you should assign before using that value..
Using it in loop statement
reverse =reverse+str.charAt(i);
And
string.length gives string length for ex:
Str="hello" ;
Length=5
But string indexes starts with 0 so max index is length-1 is 4 only for the example.
0th character is => h
1st => e
2nd => l
3rd => l
4th => o
So accessing 5th index now gives index out bounds exception...
Is it clear now......?
+ 1
import java.util.Scanner;
public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");
Scanner read = new Scanner(System.in);
String str = read.nextLine();
String reverse ;
for(int i = str.length(); i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}
System.out.println("Reversed string is:");
System.out.println(reverse);
}
}
+ 1
Is isn't giving me the result I want. I need help
+ 1
String reverse="" ;//assign before using..
And should start at i=str.length-1 in loop,...
+ 1
Okay thank you. It's working now but can you explain the logic behind that to me please
+ 1
Yes. But why must the reverse be assigned to an empty String first
+ 1
I mean the reverse variable I initiated
+ 1
reverse =reverse +str. charAt(i) ;
By this statement, first reverse value and str.charAt(i) values are taken from memory and added;, if the values are not assigned before using, then if it allowed then it uses default values otherwise throws error.
Default value for string is null, accessing null will raise exception..
Just it means accessing uninitialized location...
+ 1
Okay thanks
0
Buffered reader has a reverse method. Declare your string, and buffered reader with the string as argument. Then just say reader.reverse();
With the for loop you can reverse as well by converting the string into a character array, getting the length of the array, and starting from the length you got to 0, get the value at that index and assign it to a new string