Campbell Ritchie wrote:Welcome to the Ranch
I am afraid that main method is much too long. I think you should refactor that code to move nearly all of it out of the main method. I think you should have a ScrambledWord object which takes a word as its constructor parameter and later scrambles the field. It can have scramble and unscramble methods; the latter might have a loop where the user enters numbers to swap and stops whenever a number out of range is entered (e.g. < 0).
Don't use file input stream to read a text file. Use file reader and buffered reader, as shown in the Java™ Tutorials (look for buffered streams section).
Avoid doing arithmetic with Math#random(), despite what it says in the Java™ Tutorials. Look at this old discussion, which discusses potential errors about “random” numbers.
Never write == true or == false. Both are poor style and error‑prone. It is only a matter of time until you write = by mistake, and then your program will start to go wrong.
Not
while(userConsent == true) ...
but
while (userConsent) ...
Not
while(userConsent == false) ...
but
while (!userConsent) ...
Don't use multiple if statements for menus using 1 2 3 etc. Use switch‑case‑break.
Strings are not intended for changing; the class is immutable. That is why you are finding it so awkward to change the String. I do not think you can use a replace method on a String to achieve what you want.
There are all sorts of design advantages to making things immutable. But many immutable classes have mutable counterparts which are intended for changing. String has a mutable counterpart and here it is, specially designed for changing text rapidly and painlessly. It has methods like insert delete append and replace, so all you need to do is work out the index and the char to replace. You can even chain method calls like this:-
mutableText.insert(index1, char2).insert(index2, char1);
When you have finished with the changes, you can retrieve the text with the toString method. If you need to test for equality during that procedure try
if (mutableText.toString().equals(correctText)) ...
It would have been much easier to achieve that with arrays; you have presumably been told not to use arrays to give you more of a challenge.
How are you scrambling the word? Are you doing that programmatically or asking a user to specify letters to swap?
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |