Строка Java не меняется правильно с использованием цикла [дубликат]JAVA

Программисты JAVA общаются здесь
Anonymous
Строка Java не меняется правильно с использованием цикла [дубликат]

Сообщение Anonymous »

I am trying to write a Java program to reverse a string entered by the user.
Expected Output
Input:
hello
Output:
olleh
Actual Output
The output is incorrect or sometimes empty.
What I have tried
I used a loop to iterate through the string from the end, but I think I made a mistake in my logic.
Code
import java.util.Scanner;
public class StringReverse {

Код: Выделить всё

public static void main(String\[\] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a string: ");

String str = sc.nextLine();

String rev = "";

for(int i = str.length(); i \>= 0; i--) {

rev = rev + str.charAt(i);

}

System.out.println("Reversed string: " + rev);

}
}

Вернуться в «JAVA»