+ 1

Java challenge : reverse a string

Someone can help me with this challenge ? I found this 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(); x= arr[-1]; for(x=0;x<=arr.length;--x){ --x; System.out.println(text); } } }

26th Aug 2022, 12:07 PM
Cédric De Craim
Cédric De Craim - avatar
5 ответов
+ 2
import java.util.*; public class Program { public static void main(String[] args) { Scanner st= new Scanner(System.in); String name = st.nextLine(); System.out.println("entered string is\n"+" "+name); System.out.println("Reversed string is"); for(int x=(name.length()-1);x>=0;x--) { System.out.print(name.charAt(x)); } } }
26th Aug 2022, 1:03 PM
Harsh Nama
Harsh Nama - avatar
+ 1
x is undeclared. In java, it won't allow negative indexes. Your loop do ( assuming valid systax, then) , iterates from x = 0 to arr.length by updating x = x -2 ;// x--; x--; decrease 2, not 1 Prints 'text'. ( which is input just, not reverse string). Declare x to arr.length-1 as int x = arr.length-1; condition is x >=0; Print arr[x];
26th Aug 2022, 12:39 PM
Jayakrishna 🇮🇳
+ 1
Ok my new code is ; 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 x = arr.length -1; for(x>0;x<=arr.length;x--){ x--; System.out.println(arr[x]); } } }
26th Aug 2022, 1:03 PM
Cédric De Craim
Cédric De Craim - avatar
+ 1
for ( ; x >= 0; x--) { System.out.print(arr[ x ] ); } // print, not println //replace this, with your loop.. You declared x before loop so not adding in loop, left empty Initialization.
26th Aug 2022, 1:07 PM
Jayakrishna 🇮🇳
+ 1
Thanks a lot 😀
26th Aug 2022, 1:10 PM
Cédric De Craim
Cédric De Craim - avatar