简体   繁体   中英

Scrambling characters of String

public class WordScrambleEx1 {
    public static void main(String[] args) {
        String[] strArr = {"CHANGE", "LOVE", "HOPE", "VIEW"};

        String answer = getAnswer(strArr);
        String question = getScrambledWord(answer);

        System.out.println("Question :" + question);
        System.out.println("Answer: " + answer);
    }


    public static String getAnswer(String[] strArr) {

        String i = strArr[(int)Math.random()*4]; 
        return i;


    }
    public static String getScrambledWord(String str) { 

        char[] character = str.toCharArray();
        String question1 = null;
        for(int i = 0; i < character.length; i ++)
        {
        char[] java = new char [(int)Math.random()*i] ;
        question1 = new String(java);
        }

        return question1;
    }   
}

I am very new to Java and was given a question where I am given four letters of words and my method needs to pick one of them randomly using Math.random and scramble the characters of that string.

My code finds a String from the given array but does not scramble the string. Can anyone tell me what I am doing wrong?

Understanding constructor and scope is really hard.

first mistake:

(int) Math.random() * i

will always return 0, because Math.random() returns a float between 0 and 1, so it will always be zero when you cast it to int (int doesnt round, it just cuts off the numbers after the comma).

you can fix this by using this:

(int) (Math.random() * i)

now we are first multiplying the float result of Math.random() with i which results in a float because the first number is a float. then we are casting this float to an int.

second mistake:

public static String getScrambledWord(String str) { 

char[] character = str.toCharArray();
String question1 = null;
for(int i = 0; i < character.length; i ++)
{
char[] java = new char [(int)Math.random()*i] ;
question1 = new String(java);
}

return question1;
}   

each iteration you create a new char array with a length of 0 and then you set question1 to it, which is always an empty string because the java array has nothing in it.

i would do it as follows:

public static String getScrambledWord(String str) {
    char[] character = str.toCharArray();
    String question1 = new String();

    ArrayList<Character> chars = new ArrayList<Character>(); //an arraylist is an array wich dynamically changes its size depending on the amount of its elements
    for (int i = 0; i < character.length; i++) {// first we put all characters of the word into that arraylist
        chars.add(character[i]);
    }

    while(chars.size()>0){//then we iterate over the arraylist as long as it has more than 0 elements
        int index = (int)(Math.random() * chars.size());//we create a random index in the range of 0 and the arraylists size
        question1 += chars.get(index);// we add the letter at the index we generated to the scrambled word variable
        chars.remove(index);// then we remove the character we just added to the scrambled word, from the arraylist, so it cant be in there twice
    }// thus the size decreases by 1 each iteration until every element of the arrraylist is somewhere in the scrambled word

    return question1;
}

There are some mistakes in your code. The way you generate random integers is misleading. Let's look at the statement (int)Math.random() * 4 for an explanation. Math.random() does:

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

Now, in Java a type cast has precedence over + , - , * and / , so what actually happens is ((int)Math.random()) * 4 . Math.random() returns a floating point number between 0.0 and 1.0 exclusive , so roughly [0.0, 0.999999...]. A cast to int will truncate all decimal places and you will always get 0 . Your statement then simplifies to 0 * 4 = 0 . Overall, you always get the first word.

I recommend you to use theRandom class instead. It provides a method nextInt(int n) , which returns a random integer between 0 inclusive and n exclusive , so [0, n - 1] .

Since there are a lot of errors in your code, I would like to provide you this solution:

import java.util.Random;

public class WordScrambleEx1  {

    private static Random random;

    public static void main(String[] args) {

        // Create object of class (initializes the
        // random generator with a default seed)
        random = new Random();

        String[] strArr = { "CHANGE", "LOVE", "HOPE", "VIEW" };

        String answer = getAnswer(strArr);
        String question = getScrambledWord(answer);

        System.out.println("Question: " + question);
        System.out.println("Answer: " + answer);

    }

    public static String getAnswer(String[] strArr) {

        // Chooses a random index in [0, strArr.length - 1]
        int index = random.nextInt(strArr.length);

        String i = strArr[index];
        return i;

    }

    public static String getScrambledWord(String str) {

        String remaining = str;
        String scrambled = "";

        // Loop over the string, each time choose a random letter
        // and add it to the scrambled word, then remove that letter
        // from the remaining word. Repeat until all letters are gone.
        for (int i = str.length(); i > 0; i--) {

            // Choose the index of a letter in the remaining string
            int index = random.nextInt(remaining.length());

            // Add the letter at the random index to your scambled word
            scrambled += remaining.charAt(index);

            // Remove the chosen character from the remaining sequence
            remaining = remaining.substring(0, index) + remaining.substring(index + 1);

        }

        return scrambled;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM