简体   繁体   中英

Choosing random element from array

I have written a program that randomly selects a verb in Deutch and asks you for the Perfekt form. It continuously displays new verbs until you make a mistake. Then the program tells you your answer was incorrect and tells you how many points you have earned. The program also writes the number of points into the test.txt file and then read its number from it and after every attempt program is tracking for all-time high score.

But I want that I don't to write thousands of thousands of if statements that I have done in my first version of a program. So I have made two arrays. First array has an "question" and the second has an "answer". But I don't know how to program to generate random number and then ask this verben from first array. For example number 3 and the program select verben[2]. And look for answer verbenAnswer[2].

First program:

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);
    }
}

}

Second program:

 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);
        }
    }
}

My question: How to fix the problem with the second program, because it does not work.

Hold on to the random index you generated, and use it to index the array:

    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;
    }

You don't even need to keep the original word ( glagol ) anymore.

Simply store your random number like this:

    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;
    }

As simple as that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM