In: Computer Science
I need to reverse strings with spaces using the nextLine() with Scanner in the following code:
package Chapter8;
//To import the necessary libraries
import java.util.Scanner;
public class BackwardString
{
public static void main(String[] args)
{
//To read string from user input
String input;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter String here : ");
input=scanner.next();
//To reverse passed string
backward(input);
//To close Scanner object
scanner.close();
}
//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);
}
}
Thank you!
If you have any doubts, please give me comment...
package Chapter8;
//To import the necessary libraries
import java.util.Scanner;
public class BackwardString {
public static void main(String[] args) {
// To read string from user input
String input;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter String here : ");
input = scanner.nextLine();
// To reverse passed string
backward(input);
// To close Scanner object
scanner.close();
}
// 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);
}
}