miatech
miatech

Reputation: 2268

getting input from stdin

I want to get input from stdin in the for of

3
10 20 30

the first number is the amount of numbers in the second line. Here's what I got, but it is stuck in the while loop... so I believe. I ran in debug mode and the array is not getting assign any values...

import java.util.*;

public class Tester {   

   public static void main (String[] args)
   {

       int testNum;
       int[] testCases;

       Scanner in = new Scanner(System.in);

       System.out.println("Enter test number");
       testNum = in.nextInt();

       testCases = new int[testNum];

       int i = 0;

       while(in.hasNextInt()) {
           testCases[i] = in.nextInt();
           i++;
       }

       for(Integer t : testCases) {
           if(t != null)
               System.out.println(t.toString());               
       }

   } 

} 

Upvotes: 14

Views: 98506

Answers (2)

Yogendra Singh
Yogendra Singh

Reputation: 34367

Update your while to read only desired numbers as below:

      while(i < testNum && in.hasNextInt()) {

The additional condition && i < testNum added in while will stop reading the numbers once your have read the numbers equivalent to your array size, otherwise it will go indefininte and you will get ArrayIndexOutOfBoundException when number array testCases is full i.e. you are done reading with testNum numbers.

Upvotes: 2

mu_sa
mu_sa

Reputation: 2725

It has to do with the condition.

in.hasNextInt()

It lets you keep looping and then after three iterations 'i' value equals to 4 and testCases[4] throws ArrayIndexOutOfBoundException.

The Solution to do this could be

for (int i = 0; i < testNum; i++) {
 *//do something*
}

Upvotes: 11

Related Questions