Description Write a method that accepts a String object as an argument and displ
ID: 3582490 • Letter: D
Question
Description
Write a method that accepts a String object as an argument and displays its contents backwards. For instance, if the string argument is "gravity" the method should return "ytivarg".
In your main method, ask the user to enter the a string, call your method, and include a statement to display the results.
Requirements
Create a method that takes a string argument and returns a string
This method should return the string backwards as defined above
Add code the main method to:
request a string from the user (you may use either dialog boxes or the Scanner class to get the input)
call the method and store the result
Display the string forward and backwards
Include all usual comments at the beginning of your program, AND for the method you wrote
Explanation / Answer
import java.util.Scanner;
public class BackwardString {
private static String PrintBackward(String str) {
StringBuilder result = new StringBuilder(); // stringBuilder to append characters one by one in the end
char string[] = str.toCharArray(); //Converting the string to character array so that we can get the characters one by one
for (int i = str.length()-1; i >= 0; i--) { //Looping backwards from length of the string to zero
result.append(string[i]); //Adding the character to the result
}
return result.toString(); //Returning the result by converting it into string type
}
public static void main(String[] args){
System.out.println("Enter your string : ");
Scanner sc = new Scanner(System.in);
String str = sc.next(); //Taking user input string into variable named str
String strRev = PrintBackward(str); //Calling the method which reverses the string and assigning the result to a new variable
System.out.println("You entered :"+str);
System.out.println("Result is :"+strRev); //Printing the result
}
}
/*Sample input
Enter your string :
Computer
You entered :Computer
Result is :retupmoC*/