0

There are some assignments in Walter Savitch's Java book, where it asks you to write some code to reverse the order of a word that is entered. I came up with the following and am wondering if I could be able to optimize it as it seems a little heavy:

public static void main(String[] args) {

String statement;

System.out.print("Enter a statement to reverse: ");
statement = keyboard.nextLine();
int n;
String finalWord = "";
String letter;

for (n = statement.length(); n > 0; n--)

    {
        letter = statement.substring(0, 1);
        finalWord = letter + finalWord;
        statement = statement.substring(1);
        System.out.println(finalWord);
    }

System.out.println("Final work: " + finalWord);

Any insight would be appreciated. }

Wayne
  • 1
  • 1

2 Answers2

-1
 import java.lang.*;
 import java.io.*;
 import java.util.*;

 class ReverseString
 {
     public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter String To Reverse:- ");
    String input = sc.next();    

    // convert String to character array
    char[] arr = input.toCharArray();

    for (int i = arr.length-1; i>=0; i--)
        System.out.print(arr[i]);
}
}
Harsh Bhut
  • 238
  • 2
  • 14
  • I'm only about 250 pages into the book, so I'm not really sure what the [] means with the char there. Is that a list? – Wayne Feb 26 '18 at 18:15
  • You put this type of question and you dont know what is [ ] ?, It connert your string into char type array and then reverse print to get the reverse string – Harsh Bhut Feb 27 '18 at 03:26
-1

You can use below given code to reverse string

public class ReversString
{
    public static void main(String args[])
    {
        String name = "Vinayak Dwivedi";
        String reverseStrinf = "";
        for(int i = name.length() - 1;i >= 0  ;i--)
        {
            reverseStrinf = reverseStrinf + name.charAt(i);
        }
        System.out.println("reverseStrinf:-"+reverseStrinf);
    }
}
Vinayak
  • 11
  • 6