如何在java中防止从数组中重复选择

wz8daaqr  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(219)

我正在用jgrasp制作一个程序,将文本文件中的单词存储在数组中。有2个文件和2个数组,一个存储拼写正确的单词,另一个存储拼写错误的单词。然后程序从两个数组中随机选择一个单词,并询问用户拼写是否正确。我已经让一切运行良好,但需要一种方法,以防止单词被选中不止一次。代码如下:

import java.util.*;
import java.io.*;
public class wordGame
{
   public static void main(String[] args) throws Exception
   {
      boolean more = true;
      Scanner kb = new Scanner(System.in);
      while(more)
      {
         run(); 
         System.out.println("Another player?");
         String answer = kb.next();
         if(answer.equalsIgnoreCase("no"))
            more = false;
      }
      System.out.println("Good Bye");
   }
   public static void run() throws Exception
   {
      String[] correct = new String[10];
      String[] incorrect = new String[10];
      //static void description()
      description();
      //static void fillArray(String[] correct, String[] incorrect)
      fillArray(correct, incorrect);
      //static void play(String[] correct, String[] incorrect)
      play(correct, incorrect);
   }
   //actual play
   public static void play(String[] correct, String[] incorrect)
   {
      Scanner kb = new Scanner(System.in);
      Random rand = new Random();
      int points = 0;
      for(int i = 1; i <= 10; i++)
      {

         //genreate a random number either 0 or 1
         int r = rand.nextInt(2);
         if(r == 0)
         {
            //generate a random number between 0-9 inclusive (rand.nextInt(10))
            int index = rand.nextInt(10);
            //display the word on the string from the correct array at the given index
            System.out.println("Is the word***"+correct[index]+"***spelled correctly?");
            //ask the the user to enter if the word is spelled correctly or not y/n
            System.out.print("y/n: ");
            String answer = kb.next();
            //if the users answer is yes increment points by 1, otherwise decrement by 1
            if(answer.equalsIgnoreCase("y"))
               points++;
            else
               points--;   
         }
         else
         {
               int index = rand.nextInt(10);
            //display the word on the string from the correct array at the given index
            System.out.println("Is the word***"+incorrect[index]+"***spelled correctly?");
            //ask the the user to enter if the word is spelled correctly or not y/n
            System.out.print("y/n: ");
            String answer = kb.next();
            //if the users answer is yes increment points by 1, otherwise decrement by 1
            if(answer.equalsIgnoreCase("n"))
               points++;
            else
               points--; 
         }   
      }
      System.out.println("Your score: "+points);
   }
   public static void fillArray(String[] correct, String[] incorrect) throws Exception
   {
      //create a file object
      File f1 = new File("correct.txt");
      //create a pointer to the file
      Scanner input1 = new Scanner(f1);//input: name of scanner pulling info from file
      int index1 = 0;
      //fill in the array correct
      while(input1.hasNextLine() && index1 < correct.length)
      {
         //read one word
         String word = input1.nextLine();
         //store it in the array
         correct[index1] = word;
         index1++;
      }
      //create a file object
      File f2 = new File("incorrect.txt");
      //create a pointer to the file
      Scanner input2 = new Scanner(f2);//input: name of scanner pulling info from file
      int index2 = 0;
      //fill in the array incorrect
      while(input2.hasNextLine() && index2 < incorrect.length)
      {
         //read one word
         String word = input2.nextLine();
         //store it in the array
         incorrect[index2] = word;
         index2++;
      }      
   } 
   // displays instructions for the game
   public static void description()
   {
      System.out.printf("%40s", "Welcome to Misspelled!!");
      System.out.printf("\n%41s", "Please play resonbsibly!!");
      System.out.println("");
      System.out.printf("\n%39s", "THE RULES OF THE GAME\n");
      System.out.println("You will be shown a series of 10 words that are spelled correctly or incorrectly");
      System.out.println("Answer y if it is spelled correctly, n if it is spelled incorrectly");
      System.out.println("Correct answers will award you 1 point, incorrect answers will lose you 1 point");
      System.out.println("");

   }
}
voase2hg

voase2hg1#

这里有一个方法。我用 ints 用于演示目的,但该方法很容易适应任何数据类型。这与@scarywombat的建议类似。它在运行中进行洗牌,但仍然使用随机选择。
它只是选择一个随机值 t .
移动索引为的值 size-1 进入 t's 狭槽
更新 size 返回 t 如果没有更多值,则返回-1

int[] vals = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int size = vals.length;
Random r = new Random();

int i;
while ((i = getValue()) > 0) {
    System.out.print(i + " ");  
}

打印出类似于

3 1 8 9 10 2 6 7 4 5

方法
请注意,此方法不会保留列表的内容。如果要这样做,请取消注解注解掉的语句。但这份名单最终还是会随机化。

public static int getValue() {
    if (size > 0) {
        int idx = r.nextInt(size);
        int t = vals[idx];
        vals[idx] = vals[--size];
        // vals[size] = t;
        return t;
    }
    return -1;
}

相关问题