+ 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

12th Mar 2020, 4:31 PM
Raymond Degbe
Raymond Degbe - avatar
11 Antworten
+ 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.
12th Mar 2020, 4:33 PM
Avinesh
Avinesh - avatar
+ 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......?
12th Mar 2020, 5:10 PM
Jayakrishna 🇮🇳
+ 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); } }
12th Mar 2020, 4:47 PM
Raymond Degbe
Raymond Degbe - avatar
+ 1
Is isn't giving me the result I want. I need help
12th Mar 2020, 4:48 PM
Raymond Degbe
Raymond Degbe - avatar
+ 1
String reverse="" ;//assign before using.. And should start at i=str.length-1 in loop,...
12th Mar 2020, 4:54 PM
Jayakrishna 🇮🇳
+ 1
Okay thank you. It's working now but can you explain the logic behind that to me please
12th Mar 2020, 5:04 PM
Raymond Degbe
Raymond Degbe - avatar
+ 1
Yes. But why must the reverse be assigned to an empty String first
12th Mar 2020, 5:22 PM
Raymond Degbe
Raymond Degbe - avatar
+ 1
I mean the reverse variable I initiated
12th Mar 2020, 5:23 PM
Raymond Degbe
Raymond Degbe - avatar
+ 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...
12th Mar 2020, 5:32 PM
Jayakrishna 🇮🇳
+ 1
Okay thanks
12th Mar 2020, 5:35 PM
Raymond Degbe
Raymond Degbe - avatar
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
14th Mar 2020, 1:59 AM
Mufungo Geeks
Mufungo Geeks - avatar