首页 > 解决方案 > 如何覆盖数组?

问题描述

我正在编写一个游戏,用户必须输入从 1 到 50 的 5 个数字。这些数字被保存在数组中intPlayersNumbers。如果不满足条件,用户必须再次输入数字。为什么数组intPlayersNumbers没有被覆盖?它只保存第一次输入的数字。

public class Game {

    int chosenNumbers = 5;
    int chosenNumber;
    String numbers;
    int[] raffleArray = new int[chosenNumbers];

    public void askForNumbers(){

        Scanner in = new Scanner(System.in);
        numbers = in.nextLine();
        String[] playersNumbers = (numbers.split(" "));
        int[] intPlayersNumbers = new int[playersNumbers.length];
        for(int a =0; a<playersNumbers.length; a++ ){
            intPlayersNumbers[a] = Integer.parseInt(playersNumbers[a]);
        }
        //checking the numbers
        checkTheNumbers(intPlayersNumbers);
    }

    public int[] checkTheNumbers(int[] intPlayersNumbers){

        //if there is 5 numbers
        if(intPlayersNumbers.length==5){
            //if the numbers are form 1 to 50
            for(int i = 0; i<intPlayersNumbers.length; i++){
                if(intPlayersNumbers[i]<50 && intPlayersNumbers[i]>0){
                    continue;
                }else{
                    System.out.println("Please enter 5 nums from 1 to 50.");
                    askForNumbers();
                }
            }
        }
        else{
            System.out.println("Please enter 5 numbers");
            askForNumbers();
        }
return intPlayersNumbers;
    }

标签: javaarraysjava.util.scanner

解决方案


我认为 do-while 在这里更有意义。此外,我认为在执行验证checkTheNumbers时返回 a更有意义。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;
}

推荐阅读