Java for loop reverse a string

Question

We would like to write a program that prompts the user to enter a string.

Display the string in reverse order.

Enter a string: ABCD 
The reversed string is DCBA 
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String s = input.next();//from   ww w .  j  av  a 2s  .  c o m
        String reverse = "";
        
        //your code here
        
        System.out.print(s + " in reverse is " + reverse);

    }

}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String s = input.next();
        String reverse = "";
        for (int i = s.length() - 1; i >= 0; i--) {

            reverse += s.charAt(i);
        }
        System.out.print(s + " in reverse is " + reverse);

    }

}



PreviousNext

Related