1

i am writing a program that must scramble a word. First I read in the word backwards using .reverse. Then I turned the string into a charArray.I am suppose to create a for loop to figure out if the First letter is "A" and if it is then i have to see if the next letter is not an "A". if its not then i am suppose to swap the two letters. If any of the two letters have a;ready been swapped than they cannot be swapped again. Some examples are Input: “TAN” Output: “ATN” Input: “ALACTRIC” Output:“AALCTRIC” Input: "Fork" Output:"Fork"

Here is my code so far: i cannot figure out what to put in the for loop. Thank you!

import java.util.Scanner;

public class scrambleWordRetry {
    public static void main(String[] args)
      {
      }
    public static String scramble( Random random, String inputString)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter a word to scramble.");
        inputString = scan.nextLine();

        char a[] = inputString.toCharArray();

         for( int i=0 ; i<a.length-1 ; i++ )
            {

            }
        return inputString;     
    }
}
3
  • your code is doing nothing at the moment, since you don't call scramble() in the main method. Commented Nov 20, 2016 at 19:38
  • A lot of what you've asked is good pseudo code for what you need to do, but you haven't shown attempts to actually implement all of it yourself yet. also one side note: why take in inputString as a parameter when you immediately assign it a value. I would either remove it as a parameter, or read in the String outside the method (I would prefer this, as this allows your method to work for any string, not just one read in via a Scanner) Commented Nov 20, 2016 at 19:40
  • Homework project? Commented Nov 20, 2016 at 19:49

1 Answer 1

3

I hope this code is useful for you

    Scanner x = new Scanner(System.in);
    String str = x.next();
    System.out.println("Before Swapping" + str);
    str = scramble(str);
    System.out.println("After Swapping " + str);
}

public static String scramble(String inputString) {
    char s[] = inputString.toCharArray();
    for (int i = 1; i < s.length; i++) {

        if (s[i] == 'A' || s[i] == 'a') {
            char temp = s[i - 1];
            s[i - 1] = s[i];
            s[i] = temp;

        }
    }
    return new String(s);
}

then if you input 'ALACTRIC' the output will be 'AALCTRIC', 'Tan = aTn', 'fork = fork'.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.