如何覆盖数组?

时间:2019-06-05 13:12:32

标签: java arrays java.util.scanner

我正在写一个游戏,用户必须输入5个数字,范围从1到50。这些数字保存在数组SELECT email FROM clients WHERE date_creation >= DATE_SUB(NOW(), INTERVAL 1 HOUR); 中。如果不满足条件,则用户必须再次输入数字。为什么数组intPlayersNumbers没有被覆盖?它只保存第一次输入的数字。

intPlayersNumbers

2 个答案:

答案 0 :(得分:0)

我认为在此做些有意义的事。另外,我认为checkTheNumbers在执行验证时返回boolean更有意义。以下解决方案将不断要求输入数字,直到checkTheNumbers返回true

public int[] askForNumbers(){
    int[] intPlayersNumbers;
    Scanner in = new Scanner(System.in);
    do {
        System.out.println("Please enter 5 nums from 1 to 50.");
        numbers = in.nextLine();
        String[] playersNumbers = (numbers.split(" "));
        intPlayersNumbers = new int[playersNumbers.length];
        for(int a =0; a<playersNumbers.length; a++ ){
            intPlayersNumbers[a] = Integer.parseInt(playersNumbers[a]);
        }
    } while (!checkTheNumbers(intPlayersNumbers));
    return intPlayersNumbers;
}

public boolean checkTheNumbers(int[] intPlayersNumbers) {
    if(intPlayersNumbers.length==5) {
        for(int i = 0; i < intPlayersNumbers.length; i++) {
            if (intPlayersNumbers[i] > 50 || intPlayersNumbers[i] <= 0) {
                System.out.println("Please enter 5 nums from 1 to 50.");
                return false;
            }
        }
    } else{
        System.out.println("Please enter 5 numbers");
        return false;
    }
    return true;
}

答案 1 :(得分:-2)

我认为您可以使用递归轻松解决此问题。由于您的问题的上下文尚不完全清楚,因此我做了一两个假设。如果您想要稍微不同的解决方案,则可以使用注释作为提示。

public void askForNumbers() {

    Scanner in = new Scanner(System.in);
    // use the sout before the system.in waits for you first input
    System.out.println("Please enter 5 nums from 1 to 50.");
    numbers = in.nextLine();
    String[] playersNumbers = (numbers.split(" "));
    int[] intPlayersNumbers = new int[playersNumbers.length];
    // check if the array has lenght 5 directly after the split.
    if (intPlayersNumbers.length != 5) { // if the split.length != 5 start over
      askForNumbers();
    }
    else {
      for (int a = 0; a < playersNumbers.length; a++) {
        int i = Integer.parseInt(playersNumbers[a]); //beware this can cause a numberFormatException !!!
        if (i > 0 && i < 51) {  // if one of the number is not in range start over. 
          intPlayersNumbers[a] = i;
        }
        else {
          System.out.printf("%d was not between 0 and 50", i); // print which integer was the culprit
          askForNumbers();
          return; //return so this method ends here; 
          }
      }
      raffleArray = intPlayersNumbers; // or return intPlayersNumbers , you will have to change the return type of the method as well
    }
  }

如果您对此解决方案有任何疑问,请发表评论。