从数组中选择随机元素

时间:2014-10-22 15:19:14

标签: java arrays random

我编写了一个程序,在Deutch中随机选择一个动词,并要求您提供Perfekt表格。它会不断显示新的动词,直到你犯错。然后该程序会告诉您答案不正确,并告诉您已经获得了多少积分。该程序还将点数写入test.txt文件,然后从中读取其编号,并在每次尝试程序跟踪以获得历史最高分后。

但我希望我不要在我的第一个程序版本中编写成千上万的if语句。所以我制作了两个数组。第一个数组有一个“问题”,第二个数组有一个“答案”。但我不知道如何编程生成随机数,然后从第一个数组询问这个verben。例如3号和程序选择verben [2]。并寻找答案verbenAnswer [2]。

第一个程序:

import java.util.Random;    
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.*;

public class VerbenTest{
     public static void main(String args[]){
       String glagol;
       String correct = "Correct!";
       String incorrect = "Incorrect!";
       int j ;
       int points = 0;
       boolean answer;

    File file = new File("test.txt");


    for(int i = 0; i <= points; i++){
        Random random = new Random();


        String verben[] = {"trinken", "lesen", "schwimmen", "sterben", "fahren"};
        String verbenAnswer[] = {"hat getrunken", "hat gelesen", "hat geschwommen", "ist gestorben", "ist gefahren"};
        glagol = verben[random.nextInt(verben.length)];
        System.out.println("Please enter correct form of verb!");
        System.out.println(glagol);
        String enter = Input.readLine();

        if(glagol.equals(verben[0]) && enter.equals(verbenAnswer[0])){
            answer = true;
            points += 1;
        }else if(glagol.equals(verben[1]) && enter.equals(verbenAnswer[1])){
            answer = true;
            points += 1;
        }else if(glagol.equals(verben[2]) && enter.equals(verbenAnswer[2])){
            answer = true;
            points += 1;
        }else if(glagol.equals(verben[3]) && enter.equals(verbenAnswer[3])){
            answer = true;
            points += 1;
        }else if(glagol.equals(verben[4]) && enter.equals(verbenAnswer[4])){
            answer = true;
            points += 1;
        }else{
            answer = false;
            points += 0;
        }


        if(answer == true){
            System.out.println(correct);
        }else{
            System.out.println(incorrect);
            System.out.println("You collected: " + points + "/" + (i+1));

        }   
    }
        int highScore = 0;
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = reader.readLine();
            while (line != null) {                // read the score file line by line
                try {
                    int score = Integer.parseInt(line.trim());   // parse each line as an int
                    if (score > highScore)                       // and keep track of the largest
                        { 
                            highScore = score; 
                        }
                } catch (NumberFormatException e1) {
                    // ignore invalid scores
                    //System.err.println("ignoring invalid score: " + line);
        }
            line = reader.readLine();
    }
            reader.close();

        } catch (IOException ex) {
            System.err.println("ERROR reading scores from file");
        }

        // display the high score
            if (points > highScore){
                System.out.println("You now have the new high score! The previous high score was " + highScore + " !");
            } else if (points == highScore) {
                System.out.println("You tied the high score!");
            } else {
                System.out.println("The all time high score is" + highScore  + " !");
}
        // append the last score to the end of the file
        try {
            BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
            output.newLine();
            output.append("" + points);
            output.close();

    } catch (IOException ex1) {
        System.out.printf("ERROR writing score to file: %s\n", ex1);
    }
}

}

第二个程序:

 import java.util.Random;   
 import java.io.File;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.Scanner;
 import java.io.*;
 import javax.swing.*;
 import java.util.Date;
 import java.awt.Desktop;
 import java.io.IOException;
 import java.net.URI;
 import java.net.URISyntaxException;

public class Verben2{
   String glagol;
   String correct = "Correct!";
   String incorrect = "Incorrect!";
   int points = 1;
   boolean answer;
   boolean white = true;

public static void main(String args[]){
    new Verben2();
}
public Verben2(){
    File file = new File("test.txt");


    for(int i = 0; i < points; i++){

        Random random = new Random();

        String verben[] = {"trinken", "lesen", "schwimmen", "sterben", "fahren"};
        String verbenAnswer[] = {"hat getrunken", "hat gelesen", "hat geschwommen", "ist gestorben", "ist gefahren"};
        glagol = verben[random.nextInt(verben.length)];
        System.out.println("Please enter correct form of verb!");
        System.out.println(glagol);
        String enter = Input.readLine();
        enter = verbenAnswer[random.nextInt(verbenAnswer.length)];

        for(int j = 0; j < verben.length; j++){


            if(glagol.equals(verben[j])){
                if(enter.equals(verbenAnswer[j])){
                    answer = true;
                    points +=1;

                    }else{
                        answer = false;
                        points +=0;
                    } 
                }else{
                    answer = false;
                    points += 0;
                } 
            }

            if(answer == true){
                System.out.println(correct);
                points += 1;
            }else{
                points +=0;
                System.out.println(incorrect);
                System.out.println("You collected: " + (points -1));
            }
        }
        int highScore = 0;
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = reader.readLine();
            while (line != null) {                // read the score file line by line
                try {
                    int score = Integer.parseInt(line.trim());   // parse each line as an int
                    if (score > highScore)                       // and keep track of the largest
                        { 
                            highScore = score; 
                        }
                } catch (NumberFormatException e1) {
                    // ignore invalid scores
                    //System.err.println("ignoring invalid score: " + line);
        }
            line = reader.readLine();
    }
            reader.close();

        } catch (IOException ex) {
            System.err.println("ERROR reading scores from file");
        }

        // display the high score
            if (points > highScore){
                System.out.println("You now have the new high score! The previous high score was " + highScore + "!");
            } else if (points == highScore) {
                System.out.println("You tied the high score!");
            } else {
                System.out.println("The all time high score is " + highScore  + "!");
}
        // append the last score to the end of the file
        try {
            BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
            output.newLine();
            output.append("" + points);
            output.close();
            //new Verben();

    } catch (IOException ex1) {
        System.out.printf("ERROR writing score to file: %s\n", ex1);
        }
    }
}

我的问题:如何解决第二个程序的问题,因为它不起作用。

2 个答案:

答案 0 :(得分:2)

保持您生成的随机索引,并使用它来索引数组:

    int index = random.nextInt(verben.length);
    System.out.println("Please enter correct form of verb!");
    System.out.println(verben[index]);
    String enter = Input.readLine();

    if(enter.equals(verbenAnswer[index])) {
        answer = true;
        points += 1;
    }

您甚至不需要保留原始单词(glagol)。

答案 1 :(得分:0)

只需存储您的随机数:

    String verben[] = {"trinken", "lesen", "schwimmen", "sterben", "fahren"};
    String verbenAnswer[] = {"hat getrunken", "hat gelesen", "hat geschwommen", "ist gestorben", "ist gefahren"};
    int randomNumber = random.nextInt(verben.length);
    glagol = verben[randomNumber];
    System.out.println("Please enter correct form of verb!");
    System.out.println(glagol);
    String enter = Input.readLine();

    if(enter.equalsIgnoreCase(verbenAnswer[randomNumber])){
        answer = true;
        points += 1;
    }

就这么简单。