Home > Net >  Trying to invert the characters in a sentence
Trying to invert the characters in a sentence

Time:11-24

    Scanner input = new Scanner(System.in);
    String sentence , invertedsentence = "";
    int total , x;
    
    System.out.print("Enter your sentence:");
    sentence = input.nextLine();
    
    total = sentence.length();

I am trying to invert the characters from my input

    for ( x = total-1 ; x < 1 ; x--){
        invertedsentence = invertedsentence   sentence.charAt(x);
    }
    

The output shows blank

    System.out.println(invertedsentence);

CodePudding user response:

It should be x>=0

for (int x = total-1 ; x >= 0 ; x--){
    invertedsentence = invertedsentence   sentence.charAt(x);
}

CodePudding user response:

Have you tried:

new StringBuilder(input).reverse().toString();

So it gets less complicated ?

If you are trying to solve a problem, your for loop is wrong. First one "x < 1" should be x >= 0 because you need to go to the last index:

for ( x = total-1 ; x >= 0 ; x--)

Full example:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String sentence = "";
    int total , x;

    System.out.print("Enter your sentence:");
    sentence = input.nextLine();
    total = sentence.length();

    String invertedsentence = "";

    for ( x = total-1 ; x >= 0 ; x--){
        invertedsentence  = (Character.toString(sentence.charAt(x))   "");
    }

    System.out.println(invertedsentence);
}

CodePudding user response:

The logic is wrong. It should be

for ( x = total-1 ; x >= 0 ; x--){ 
    invertedsentence = invertedsentence   sentence.charAt(x);
}

Also, suggest to use StringBuilder/StringBuffer(which is a thread safe implementation) instead of directly concatenating the string since every time you concatenate a string, you are creating a new copy of the string and referencing that which can be really bad especially if the string you want to invert is a big one i.e. use something like:

Scanner input = new Scanner(System.in);
String sentence;
StringBuilder invertedsentence = new StringBuilder();
int total , x;

System.out.print("Enter your sentence:");
sentence = input.nextLine();

total = sentence.length();
for ( x = total-1 ; x >= 0 ; x--){
    invertedsentence.append(sentence.charAt(x));
}
System.out.println(invertedsentence.toString());

CodePudding user response:

I am assuming this is a homework and your professor is interested in teaching you how to manipulate arrays.

A String object is backed by an array of characters. Therefore, you need to reverse the order of the elements in the array. SPOILER ALERT: You can easily do this by calling StringBuilder#reverse() method, but that is not what the assignment requires you to do.

There are two solutions that should work for your assignment. One is creating a new array where the last character in the original array is placed in the in the first index of a new array. Therefore, you will need a loop that goes from string length - 1 down to zero so that you could move a pointer on the characters of the original array.

The second solution is to do it in place. For this, you will swap the first and last elements and move two pointers from the ends of the array inwards towards the middle. You will need a temporary char variable that will hold one of the values in order to complete the swap. In this case, you will increment the left pointer (head) and decrement the right pointer (tail) until they overlap (when the value of the left pointer is greater or equal to the right pointer).

I won't code it because this is a homework and you need to figure this on your own. But this is sufficient information for you to accomplish that.

UPDATE: I changed my mind. Here are the solutions for what I described above.

public class ReversedString {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a word or sentence: ");
        String str = scanner.nextLine(); // i.e. Hello World!
        scanner.close();
        
        // in-place solution
        int headPtr = 0;
        int tailPtr = str.length() - 1;
        char temp;
        char[] arr = str.toCharArray();
        while (headPtr <= tailPtr) {

            temp = str.charAt(headPtr);
            arr[headPtr] = str.charAt(tailPtr);
            arr[tailPtr] = temp;
            headPtr  ;
            tailPtr--;
        }
        
        String reversedString = new String(arr);
        System.out.println("Reversed String: "   reversedString); // !dlroW olleH
        
        
        // two-array solution
        char[] newArr = new char[arr.length];
        for (int i = arr.length - 1, j = 0; i >= 0; i--, j  ) {
            newArr[j] = arr[i];
        }
        
        reversedString = new String(newArr);
        System.out.println("Reversed String: "   reversedString); // Hello World!
    }
}

Obviously, you need only one. While the two-array solution looks cleaner and might be OK for most cases, if you are dealing with extremely large strings, it might not be optimal because you use more memory. The in-place solution addresses that because all of the array manipulation is done in the original array by moving one of the characters to a temporary value in order for the swapping of characters to work.

I believe this is what your professor expects you to be able to do for this homework.

  • Related