argentage
argentage

Reputation: 2778

How can I use Scanner.hasNext to fill multiple array values?

I have a series of dice and for each one, I need to prompt the user if they'd like to reroll it or not. The simplest way seems to be a prompt with the Scanner class- I check to see what they enter and handle appropriately. However, scanner.next() will throw an exception if the requested data doesn't exist in the user input. So, scanner.hasnext() needs to fit in here somehow.

This is the code I have; it will enter the entries into the response array but will throw an exception if the user input contains neither Y nor N.

public Boolean[] chooseDice(int diceNum){
    Boolean[] responses = new Boolean[diceNum];
    Scanner scansworth = new Scanner(System.in);
    for (int i=0; i<diceNum; i++){
        System.out.printf("Reroll this die? (%d)\n",i);
                responses[i] = (scansworth.next("[YN]")) == "Y" ? true : false;
    }
        return responses;

How do I call scansworth.hasNext("[YN]") so that the intepreter doesn't lock and so that it correctly checks for entry after each step of the loop?

Upvotes: 0

Views: 1988

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213351

You can surround the code reading user input with a while, to check whether a user input is in given pattern.... using hasNext("[YN]").. Also, you don't need scanner.next([YN]).. Just use next().. It will fetch you the next line entered, and you can compare it with "Y"..

 for (int i=0; i<diceNum; i++){
           int count = 0;
           System.out.printf("Reroll this die? (%d)\n",i);

           // Give three chances to user for correct input.. 
           // Else fill this array element with false value..

           while (count < 3 && !scansworth.hasNext("[YN]")) {
               count += 1;  // IF you don't want to get into an infinite loop
               scansworth.next();
           }    

           if (count != 3) {
                /** User has entered valid input.. check it for Y, or N **/
                responses[i] = (scansworth.next()).equals("Y") ? true : false;
           } 
           // If User hasn't entered valid input.. then it will not go in the if  
           // then this element will have default value `false` for boolean..
 }

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

I think you can try something like this.....

public Boolean[] chooseDice(int diceNum){
    Boolean[] responses = new Boolean[diceNum];
    boolean isCorrect = false;
    Scanner scansworth = new Scanner(System.in);
    for (int i=0; i<diceNum; i++){

while(!isCorrect){

if((scansworth.hasNext().equalsIgnoreCase("Y")) ||  (scansworth.hasNext().equalsIgnoreCase("N")))`{



    responses[i] = scansworth.next();
    isCorrect = true;

}else{

       isCorrect = false;


    }
  }

}

Upvotes: 0

Related Questions