I need to convert list in java into java array with while loop

129 views Asked by At

I get the question about choosing a random word from user input using Knuth's shuffling algorithm, but the problem is I have the constraint of using some specific libraries.

(here is the link for more details - my part is to form the random word java file) https://coursera.cs.princeton.edu/algs4/assignments/hello/specification.php

My main problem is, my program accepts the user's input in form of a string list and uses the while-loop to add more detail, but to apply the algorithm I must convert the list into arrays; however, the program doesn't get my data and it always returns an empty array. What should I do, thanks in advance!

Here is my code:

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class RandomWord {

    public static void main(String[] args) throws IOException {
        StdOut.println("enter your words"); // StdIn.hasNextChar() = !StdIn.isEmpty()
        ArrayList<String> mylist = new ArrayList<String>();
        String store = new String();
        int count = 1;
        String[] arr = new String[mylist.size()];
        int k = 0;
        store = StdIn.readString();
        mylist.add(store);
        if (StdIn.hasNextChar() == false || mylist.contains(null)) {
            StdOut.println("you enter nothing");
        }
        else {
            while (count == mylist.size()) {
                while (StdIn.hasNextChar() == true) {
                    store = StdIn.readString();
                    mylist.add(store);
                    count++;
                    mylist.toArray(arr);
                    System.out.println(Arrays.toString(arr));
                }
            }
        }
    }
}

Here is my test result:

enter your words

hi ho // my input from the terminal

[] // the result: an empty array - not what I want

Notice: If I use System.out.println(mylist) it still prints for me the ArrayList full of input ( [ hi, ho] ) but I think that is the list - not the array, in case if I can shuffle the list entries, can anyone show me how to do that in the simplest ways with Knuth's algorithm!

I try to add more specific constraints, such as the while-loop may end when the list size == the number of words the user adds into the program, but It doesn't work as I think

I expect the data can convert from strings -> a String[] but don't have to go through the list conversion

1

There are 1 answers

0
donvogel On BEST ANSWER

Your problem is folowing line

mylist.toArray(arr);

The toArray method return the filled array. the parameter is only for init of the new array.

Try the follwowing

arr = mylist.toArray();