213k views
3 votes
Write a method that accepts a String object as an argument and displays its contents backward. For instance, if the string argument is "gravity" the method should display "ytivarg". Demonstrate the method in a program that asks the user to input a string and then prints out the result of passing the string into the method.

User Kangear
by
4.6k points

1 Answer

7 votes

Answer:

// importing the necessary libraries

import java.util.Scanner;

public class BackwardString {

public static void main(String[] args) {

String input;

// Scanner object to read string from user input

Scanner scanner = new Scanner(System.in);

System.out.print("Enter String here : ");

input=scanner.next();

// calling backward method to reverse passed string

backward(input);

// closing Scanner object

scanner.close();

}

// Method to Reverse the input string

private static void backward(String source) {

int i, len = source.length();

StringBuilder dest = new StringBuilder(len);

for (i = (len - 1); i >= 0; i--){

dest.append(source.charAt(i));

}

System.out.println("Reversed String : "+dest);

}

}

Step-by-step explanation:

// importing the necessary libraries

import java.util.Scanner;

public class BackwardString {

public static void main(String[] args) {

String input;

// Scanner object to read string from user input

Scanner scanner = new Scanner(System.in);

System.out.print("Enter String here : ");

input=scanner.next();

// calling backward method to reverse passed string

backward(input);

// closing Scanner object

scanner.close();

}

// Method to Reverse the input string

private static void backward(String source) {

int i, len = source.length();

StringBuilder dest = new StringBuilder(len);

for (i = (len - 1); i >= 0; i--){

dest.append(source.charAt(i));

}

System.out.println("Reversed String : "+dest);

}

}

The program above accepts a String object as an argument and displays its contents backward.

It reverses the any string inputed while producing the output.

User Gs Hurley
by
4.6k points