-1

My scanner is not detecting my first input, but it is detecting the second. More info below.

Here's my code:

static int rows = 5; static int columns = 4; static int elementsEntered = 0;
static boolean leave = false;
static Scanner s = new Scanner(System.in);
static String input;


int[][] iarray = new int[rows][columns];
//Populates int array
System.out.println("In the int array");
for(int r = 0; r<iarray.length; r++) //runs through each row
{
  for(int c = 0; r<iarray[0].length; c++) //runs through each column
  {
    System.out.println("Enter the next Element: (or @ to stop)");
    input = s.next();
    if(s.hasNext() && input.equals("@")) //sentinel condition
    {
      leave = true;
      break;
    } else if (s.hasNextInt()) //populates array with inputs
    {
      iarray[r][c] = s.nextInt();
      elementsEntered++;
      s.nextLine();
    } else
    {
      leave = true;
      break;
    }
  }
  if(leave)
  {
      break;
  }
}

When I run it nothing happens after the first time I type something and press enter. Likewise, nothing happens if I press enter multiple times. But the second time I enter a value and press enter, then it gets entered into the array. Also, my sentinel condition faces the same issue.

So why is my scanner not detecting the first value I enter? I assume its something with the scanner functions I'm using but I can't figure out why.

Thanks

Edit: I found a solution. I removed the s.hasNext() and s.hasNextInt conditions and I changed

input = s.next();

to

input = s.nextLine();

and got the int value by parsing it from input.

Ganlas
  • 51
  • 5

1 Answers1

1

I think that previous response could help you to improve your code and solve the issue. Enhanced for loop does not work with Scanner inside loop body

Is not a good practice break the loop. for that particular event you can use the second parameter of the for loop for example

for(int c = 0; r<iarray[0].length && !leave; c++){...