Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting input from stdin

Tags:

java

io

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());               
       }

   } 

} 
like image 722
miatech Avatar asked Oct 27 '12 00:10

miatech


People also ask

How do you get user input from stdin in Python?

Read Input From stdin in Python using input() The input() can be used to take input from the user while executing the program and also in the middle of the execution.

What does read input from stdin mean?

Short for standard input, stdin is an input stream where data is sent to and read by a program. It is a file descriptor in Unix-like operating systems, and programming languages, such as C, Perl, and Java.

How do you read two integers from stdin in Python?

Read two integers from STDIN and print three lines where: The first line contains the sum of the two numbers. The second line contains the difference of the two numbers (first - second). The third line contains the product of the two numbers. print (sum) #The first line contains the sum of the two numbers.

What is stdin input and output?

The standard input device, also referred to as stdin , is the device from which input to the system is taken. Typically this is the keyboard, but you can specify that input is to come from a serial port or a disk file, for example.


1 Answers

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*
}
like image 104
mu_sa Avatar answered Oct 01 '22 16:10

mu_sa