我需要一个循环来询问用户5次1到10之间的数字

vh0rcniy  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(214)

在这个函数中,我需要一个循环,要求用户输入5个介于1和10之间的数字,并将这些数字存储在数组调用numarray中。我需要验证用户的输入。我知道我需要另一个循环的地方,将允许用户输入5个不同的数字,但我不知道放在哪里。

public class numberInput {
static int number;

static Scanner keyboard = new Scanner(System.in);

public static void main(String[] args) throws IOException {

    // Calls inputNumbers function
    inputNumbers();

}

// inputNumbers function
public static void inputNumbers() {

    System.out.println("Please enter 5 numbers between 1 and 10.");
    number = keyboard.nextInt();

    // If below is true display error message
    while (number <= 0 || number > 10) {

        System.out.println("Error: Enter a number BETWEEN 1 and 10.");
        number = keyboard.nextInt();

    }

}
}
enyaitl3

enyaitl31#

就像这样,要求5个不同的数字:

public static void inputNumbers() {
        ArrayList<Integer> al = new ArrayList<Integer>();
        System.out.println("Please enter 5 distinct numbers between 1 and 10.");
            for(int i = 0;i<5;i++) {
                number = keyboard.nextInt();

                // If below is true display error message
                while (number <= 0 || number > 10 || al.contains(number)) {//al.contain(number) means does al have number in it

                    System.out.println("Error: Enter a number BETWEEN 1 and 10.");
                    number = keyboard.nextInt();

                }
                al.add(number);//now add the number into the arraylist
            }
}

如果需要数组,请执行以下操作:

int[] numArray = new int[];
numArray = al.toArray(new int[0]);

相关问题