+ 2
Reverse a String (Java)
Hey Guys, i know this is the right code for reversing a string but i don't understand why. 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(); //your code goes here String rev =""; for (char i : arr) rev = i + rev; System.out.println(rev); } } Where is the Point the scanner puts the String into the Char Array ? Iam nearly new in Java and don't understand this... Thx
5 ответов
+ 5
// get the string (text) from user
String text = scanner.nextLine();
// put the string into the char array
char[] arr = text.toCharArray();
// create an empty string (rev)
String rev ="";
// loop over char array (store each char in i)
for (char i : arr)
// add char (i) at start of rev string
rev = i + rev;
// print rev string
System.out.println(rev);
/*
given string text == "abc"
arr == [ 'a', 'b', 'c' ]
rev == ""
start loop:
i == 'a'
rev == 'a' + "" == "a"
i == 'b'
rev == 'b' + "a" == "ba"
i == 'c'
rev == 'c' + "ba" == "cba"
end loop
print rev == "cba"
*/
+ 2
No worry. It was a mistake nobody hurt xP
+ 1
Ok 👌 Thank you . Think i got it 😅
+ 1
why did you set and remove best answer mark, so?