0

The code in the description is supposed to reverse a string but its just printing the last letter please help me

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(); char[] res = new char [arr.length]; //your code goes here int length = arr.length; for (int i = 0; i < arr.length; i++){ for (char b: arr){ res[i] = b; } }System.out.println (res); } }

26th Jun 2022, 4:24 PM
Pro
Pro - avatar
3 Antworten
+ 1
Remove inner loop ; // for ( chat b : arr) , no need and then insert in reverse arr.length -1 to 0; not from 0 to arr.length your loop mentaining only last values in each index. oh. you need to give a one more try.. you can reply again with your update, if you have any errors again...Dennis Besic
26th Jun 2022, 4:26 PM
Jayakrishna 🇮🇳
+ 1
You can link your code like this: Go to Code section, click +, select the programming language, insert your code, save. Come back to this thread, click +, Insert Code, sort for My Code Bits, select your code.
26th Jun 2022, 4:27 PM
Lisa
Lisa - avatar
0
Consider the following: i = 0 and the word is "hello". Then the for each loop does this res[0] = 'h' res[0] = 'e' res[0] = 'l' res[0] = 'l' res[0] = 'o'
26th Jun 2022, 4:33 PM
Lisa
Lisa - avatar