0
        String sql_query = "SELECT * FROM words";
        ResultSet rs = statement_object.executeQuery(sql_query);
        List<String> wordsList = new ArrayList<>();
        int size = wordsList.size();
        System.out.println("Enter the number of words you want to sort");
        int numWords = input.nextInt();
        int j4 = 0;
        while (rs.next()) {
            String words = rs.getString("Word");
            words = words.toLowerCase();
            dictionaryWords.add(words);
            j4++;
            
            for (int i = 0; i < numWords; i++) {
                String [] randomWords = new String[numWords];
                Random rand = new Random();
                System.out.println(words);
            }
            }

The code prints the words in my database repetitively. For example,

Enter the number of words you want to sort: 3

Ape

Ape

Ape

Rose

Rose

Rose

Bite

Bite

Bite

I need it to print to pull 3 random words from the database (or whatever given input) and print that result. For example, Enter the number of words you want to sort: 3

Ape

Rose

Bite

M S
  • 1
  • 2
    I'd break this down: **a.** Do the query (if there's only one column required, don't `SELECT *`, just the necessary column). **b.** Add the words to your `List`. **c.** Call `Collections.shuffle` on the `List` and remove the first n words. Take a copy first if you like – g00se Aug 12 '21 at 23:06

2 Answers2

1

There are two questions here:

  1. why is my code printing each word three times, and
  2. how do I print three random words from the database?

Q1

To answer the first question, please read what your code is doing carefully:

  • the while loop iterates over each row in the database:
    • while (rs.next())
  • the for loop iterates the number of times you input into numWords:
    • for (int i = 0; i < numWords; i++)
  • the println prints the word it just read from the database:
    • String words = rs.getString("Word");
    • System.out.println(words);

So, if you think about it, it's saying "for each word in the database, loop three times and print that word". Which is exactly what you've observed.

Q2

To answer the second questions,

  1. I would first get all words from the database and put that into an array. That's what you've done with dictionaryWords:

    • dictionaryWords.add(words);
  2. Then I would loop numWords time. So pull the for loop outside of the while loop.

  3. Then on each iteration of the loop, get a random word from dictionaryWords. Your code is not actually using the rand object you created. Take a look at this Stackoverflow question for examples on how to use it:

Caleb
  • 524
  • 5
  • 18
  • 2
    Take a look at [Creating random numbers _with no duplicates_](https://stackoverflow.com/questions/4040001/creating-random-numbers-with-no-duplicates). But shuffling a list (as per go00se's [comment](https://stackoverflow.com/questions/68764866/printing-an-array-of-random-words-given-the-number-of-words-requesed-by-input-in#comment121527407_68764866) in the question) is probably the simplest way. – andrewJames Aug 13 '21 at 00:08
0

Maybe it better to get the exact result from the database:

//add order by if want the result to be shuffle
//MSQL
select top 3 distinct(word) from words ORDER BY NEWID()

//mysql
select distinct(word) from words ORDER BY RAND() limit 3 
...etc (see exact syntax for your rdbms)

Note: Order by can have a second parameter to refine sort but in case on first criteria random will not work.

Doing additional java-processing is time consuming. Besides that, if you all records and columns you will increase query execution time.

If really want to retrieve all words then you could use a Set to store only distinct words, but still need to transfer to a List in order to shuffle and after sort. Here it's now up to you how it's better to procced.

Still there is a work around using subquery.

//mysql
select w.word
from
    (
      select distinct(word) word 
      from words 
      order by rand() 
      limit 3
    ) w
order by w.word desc //asc default

Or just sort it from java having still an enhancement, maybe using a TreeSet which retain elements sorted, etc.

Traian GEICU
  • 1,750
  • 3
  • 14
  • 26