-1

我将如何做到这一点,以使所说的行array.equals(guess)有效,以及如何将加载值方法更改为不允许重复数字?

import java.util.Arrays;
import java.util.Random;
import javax.swing.JOptionPane;

public class Assignment {

    private static int[ ] loadValues(){
        int[] groupOfValues = new int[5];
        Random randomized = new Random();

        for (int index = 0; index < 5; index++) {
          groupOfValues[index] = randomized.nextInt(39) + 1;
        }
        return groupOfValues;
    }
    private static void displayOutcome(int [ ] array, int guess){
          if(array.equals(guess)){
          JOptionPane.showMessageDialog(null, "Congrats, your guess of " + guess + " was one of these numbers:\n" 
                  + Arrays.toString(array));
          }
          else{
          JOptionPane.showMessageDialog(null, "Sorry, your guess of " + guess + " was not one of these numbers:\n" 
                  + Arrays.toString(array));
          }

    }

    public static void main(String[] args) {

          int guessedConvert;
          String guess;

          do{
          guess = JOptionPane.showInputDialog("Guess a number from 1-39");
          guessedConvert = Integer.parseInt(guess);     
          }while(guessedConvert < 1 || guessedConvert > 39);

          displayOutcome(loadValues(), guessedConvert);



    }
}
4

1 回答 1

3

搜索数组需要一个循环:

boolean found = false;
for (int i = 0 ; !found && i != array.length ; i++) {
    found = (array[i] == guess);
}
if (found) {
    ...
}

要确定是否存在重复项,请在外循环loadValues添加类似的代码段:

for (int index = 0; index < 5; index++) {
    boolean found = false;
    int next = randomized.nextInt(39) + 1;
    // Insert a loop that goes through the filled in portion
    ...
    if (found) {
        index--;
        continue;
    }
    groupOfValues[index] = next;
}
于 2013-04-16T23:56:37.883 回答