0

So I have this this code:

int[] player1 = new int[5]; // first player
            try{

               for(int i=0;i<5;i++) {

                   player1[i] = keyin.nextInt();}
               }
           catch(NumberFormatException e){

               System.out.println("Player 2 : ")

           }
int[] player2 = new int[5]; // Second Player

                try{

               for(int i=0;i<5;i++) {

                   player2[i] = keyin.nextInt();}
               }
           catch(NumberFormatException e){

               System.out.println("Player 3 : ");  
           }                  

I'm trying to get the user to input 5 or less integers for betting purposes, but somehow my code keeps forcing the user to input 5 orelse it won't catch and go to the second player.. How do I change this?

5
  • nextInt should be followed by nextLine to remove the carriage return which still remains within the System.in buffer...otherwise nextInt will fail the next time it is called Commented Feb 12, 2015 at 0:33
  • @MadProgrammer How would I write that exactly? (Newbie coder!) Commented Feb 12, 2015 at 1:32
  • keyin.nextLine(); ... Commented Feb 12, 2015 at 1:35
  • @MadProgrammer You said followed by nextLine? Commented Feb 12, 2015 at 1:38
  • Sorry, copy and paste Commented Feb 12, 2015 at 1:38

1 Answer 1

2

You're using a for loop to request that the user inputs 5 numbers

for(int i=0;i<5;i++) {

                   player1[i] = keyin.nextInt();}
               } 

This is saying that the user must input a number until i increments itself to 5, meaning 5 inputs.

What you could do is make a while loop saying:

while(keyin.hasNextInt()){

}

And then use an if statement that breaks out of the loop once the input reaches 5 characters, or if the user breaks out of the loop by pressing a key on the keyboard.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm trying to make it so the user only has to press anything else but an int it has to look like Player1: 1 2 3 4 and on the following line Player2: 3 2 1
I would put the while loop outside the for loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.