dimanche 10 mai 2020

How can I specify what numbers should an array accept from a scanner

public static void main(String[] args) {
    Scanner input =  new Scanner(System.in);
    boolean isArrayInputStillGoing = true;
    while (isArrayInputStillGoing){
    System.out.println("Please enter the size of the array");
    int sizeOfArray = input.nextInt();
    if (sizeOfArray < 0){
        System.err.println("Array cannot have a negative value try again");
        continue;
    }
    int[] initialArray = new int[sizeOfArray];
    System.out.println("Please enter the array elements");
    for (int i=0;i<sizeOfArray;i++){
        initialArray[i] = input.nextInt();
        if (initialArray[i] <= 0 || initialArray[i] > 100){
            System.out.println("Try again with a number between 1 and 100");
            continue;
        }
    }
    isArrayInputStillGoing = false;
        renderArray(initialArray);
    }
}

How can I make it so when a number less than 1 or more than 100 is inputed it requiers you to input that same number again. As is it just prints out the message and then prints the array with any inputed numbers even if they are wrong. Also it is saying that the continue is unneccesary since it is the end of the loop.

Aucun commentaire:

Enregistrer un commentaire