Java – word scrambler [keeping first and last letter] Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Java – word scrambler [keeping first and last letter] without wasting too much if your time.

The question is published on by Tutorial Guruji team.

My assignment is to write a program to scramble a word while maintaining the same first and last letter and only swapping two letters, then prompt the user to continue if they wish.

Example: userInput = bacon | Output = bcaon

I’ve attached an imagine of my program, there may be several issues, but as it stands I can’t really run it due to the errors in the image. I’m really confused because I got a TA to help me on this assignment, and they seemed to think this would definitely work, but as you can see it does not.

I would really appreciate if someone could tell me what exactly is wrong and why. And if you have anything to add to make this program work, I’d really, really appreciate that too, but bottom line is I just want to understand what’s wrong and why.

import java.util.Scanner;
import java.util.Random;
public class FreeStyle {

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);                        // Importing and initializing keyboard to 'in'
    System.out.println("Please enter a word to be scrambled"); // Asking user for a word
    String word = in.next();                               // Initializing the user's input 
    System.out.println(swapLetters(word));                    

    System.out.println("Would you like to enter another word? y/n");
    String answer = in.next();
    boolean userDone = true; //Using a Boolean statement to ask the user if they are done enter words or not
    while (userDone) {

        if (answer.equals('y')) {
            System.out.println("Please enter a new word");      //Ask user for new word to scramble
            word = in.nextLine();                                   //New initialization for 'word'
        } else if (answer.equals('n')) {                            //If user types 'n', loops then breaks because while(userDone) is false
            userDone = false;
        } else {
            System.out.println("Invalid input, please enter more than 3 letter words."); // The logic doesn't flow or apply to words that are less than 4 letters, so this catches that error and notifies the user
        }
    }
}

private static String swapLetters(String word) { //Private method used for the program only, no need to involve the user

    Random r = new Random(); //Using random instead of math floor
    //int arraysize = word.length();
    int a = r.nextInt(word.length()-2)+1; 
    int b = r.nextInt(word.length()-2)+1;
    //String word2 = word.substring(a, a+1);    
    String word2 = word.substring(0, a) + word.charAt(b)+word.substring(a+1, b)+word.charAt(a)+word.substring(b+1);
    return word2;
}

Answer

Several points:

  1. Why not use something already done exactly for what you are trying to do – Collections.shuffle? See comments in the code for understanding how it works.
  2. You can’t use equals() between a String and a char (‘ ‘ are for chars, ” ” are for Strings). Simple fix – just put your ‘y’ into “y”, same for ‘n’.
  3. I’ve refactored the code at the beginning that we used to get user input and then scramble into a separate method, so we can reuse it again – getInputAndScramble.
  4. And finally, I’ve used a do-while loop to keep looping until the user stops the loop with the “n” letter.

Please see my comments in the code, hopefully will clear things up.

public class Scrambler {

    public static void main(String[] args) {

        boolean userDone = true; 
        String word;

        Scanner in = new Scanner(System.in);                      
        getInputAndScramble(in); //Extracted method to get Scanner input and scramble

        do {
            System.out.println("Would you like to enter another word? y/n");
            word = in.next();
            while (userDone) {
                if (word.equals("y")) {
                    getInputAndScramble(in);
                    break;
                } else if (word.equals("n")) {                          
                    userDone = false;
                } else {
                    System.out.println("Invalid input, please enter more than 3 letter words."); 
                }
            }
        } while (userDone); //continue until "n"
    }

    private static void getInputAndScramble(Scanner in) {
        System.out.println("Please enter a word to be scrambled"); 
        String word = in.next();                               
        System.out.println(swapLetters(word));
    }

    private static String swapLetters(String word) { 

        /* Convert word into an ArrayList of characters. 
           Create ArrayList size of word, 
           convert String word into a char array and insert every char in                
           the char array into our ArrayList.
        */

        ArrayList<Character> chars = new ArrayList<>(word.length());
        for (char c : word.toCharArray()) {
            chars.add(c);
        }

        //Shuffle, omitting first and last letters
        Collections.shuffle(chars.subList(1, chars.size()-1));

        //Add shuffled letters into an array to output as a word entity
        char[] shuffled = new char[chars.size()];
        for (int i = 0; i < shuffled.length; i++) {
            shuffled[i] = chars.get(i);
        }
        //Return shuffled String
        return new String(shuffled);
    }
}
We are here to answer your question about Java – word scrambler [keeping first and last letter] - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji