+ 1

Hi guys I'm new in java can anyone help me to print out a reversed string this my code:

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine(); char[] arr = text.toCharArray(); int i,j; j=text.length; for(i=0;i<arr.length;i++){ arr[i]=text[j]; --j; } for(i=0;i<arr.length;i++){ System.out.print(arr[i]); } } }

16th Sep 2021, 10:25 AM
Coderalgeria
Coderalgeria - avatar
14 Respostas
+ 4
just replace String sample = "Sample string"; with String sample = new Scanner(System.in).nextLine(); for getting input
16th Sep 2021, 12:52 PM
GHOST mHBr
GHOST mHBr - avatar
+ 3
Try iterating through your input in reverse with your for loop. Example: public class Program { public static void main(String[] args) { for(int i=9; i>=0; i--){ System.out.println(i); } } }
16th Sep 2021, 10:42 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
String text = sc.nextLine(); StringBuilder sb = new StringBuilder(text); System.out.println(sb.reverse().toString());
16th Sep 2021, 1:39 PM
Niththish
Niththish - avatar
+ 3
Martin Taylor Niththish I see thank u all ,I really apericiate it
16th Sep 2021, 1:48 PM
Coderalgeria
Coderalgeria - avatar
+ 2
GHOST mHBr thank u
16th Sep 2021, 12:59 PM
Coderalgeria
Coderalgeria - avatar
+ 2
import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine(); char[] arr = text.toCharArray(); int i; for(i=arr.length-1;i>=0;i--){ System.out.print(arr[i]); } } }
17th Sep 2021, 9:37 AM
Coderalgeria
Coderalgeria - avatar
+ 2
import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner in = new Scanner(System.in); String text = in.nextLine(); for (int i=text.length()-1;i>=0;i--) System.out.print(text.charAt(i)); } }
24th Sep 2021, 6:26 AM
Sugandha Das
+ 1
reverse() is the key! But you can do this by yourself: something like this: String sample = "Sample string"; String rev = ""; int r=0; for (int i=0 ; i < sample.length() ; i++){ r = sample.length()-i; rev.charAt(i) = sample.charAt(r); { System.out.println(rev);
16th Sep 2021, 10:35 AM
GHOST mHBr
GHOST mHBr - avatar
+ 1
This will work: public class Program { public static void main(String[] args){ String sample = "Sample string"; char rev[] = sample.toCharArray(); int r=0; for (int i=0 ; i < sample.length() ; i++){ r = sample.length()-i-1; rev[i] = sample.charAt(r); } System.out.println(rev); } }
16th Sep 2021, 11:43 AM
GHOST mHBr
GHOST mHBr - avatar
+ 1
GHOST mHBr I know but I want the user to input the string!
16th Sep 2021, 11:54 AM
Coderalgeria
Coderalgeria - avatar
16th Sep 2021, 12:56 PM
GHOST mHBr
GHOST mHBr - avatar
0
Rik Wittkopp when i compile it , an error message appears indicating there is a problem in line 12
16th Sep 2021, 11:08 AM
Coderalgeria
Coderalgeria - avatar