samedi 19 septembre 2020

how to remove random string from array list java

I am currently learning Java. I am writing the code for a guessing game. Need to create a playGame() method with multiple different conditions.

The method should generate a random number from 1 to 10 inclusive. In a while loop the method should prompt the user to guess a number between 1 and 10.

If the user guessed the number correctly, he or she wins a randomly chosen quotation (stored in the array list). And this quotation object then should be deleted using method deleteQuotation().

Here is my code:

public void playGame() {
    Random rand = new Random();
    int randomNumber = rand.nextInt(10)+1;
    System.out.println("Random number is: " + randomNumber);
    boolean win = false;
    while(win == false) {
        InputReader myIr1 = new InputReader();
        System.out.println("Type any integer number between 1 and 10:");
        int guess = myIr1.readInt();
        //System.out.println("You entered this number: " + guess);
        if(guess == randomNumber) {
            win = true;
            System.out.println("You guessed the random number!");
            System.out.println("Here is the quotation for you:");
            GuessingGame myGg1 = new GuessingGame();
            myGg1.populateQuotationList();
            int listSize = myGg1.getListSize();
            int[] values = new int[listSize];
            Random rand1 = new Random();
            int index = rand1.nextInt(values.length);
            myGg1.getQuotationByIndex(index);
            String s1 = myGg1.getQuotationList().get(index).toString();
            
            myGg1.deleteQuotation(s1);
            
            }
      }
}

Here is my deleteQuotation() method:

public void deleteQuotation(String quotation) {
    Iterator <Quotation> it = quotationList.iterator();
    while(it.hasNext()) {
        Quotation q = it.next();
        if(q != null) {
            it.remove();
        }
    }
}

After executing this code, getListSize() is 0, while it is expected to be 4. Not sure how to pass the random string to deleteQuotation() method. Any advise would be appreciated.

Thank you




Aucun commentaire:

Enregistrer un commentaire