GETTING INPUT

SCENARIO 2B
GETTING n DATA SPACE DELIMITED ON A SINGLE LINE (n is determined at run-time)

 

This is a common enough scenario found on the CCC.  Thankfully, it is very easy to deal with in Java.


SAMPLE INPUT 1

               5 4 1 0 4 5


SAMPLE INPUT 2

               3 dog cat mouse

 

Here are a few examples:

 

EXAMPLE 1 – INTEGERS

 

Below is an example where the program has to handle many numbers separated by a space on a single line.  The first number states how many other numbers there are in the line.

 

import java.util.Arrays;

import java.util.Scanner;

 

public class InputBasics 

{

       public static void main(String[] args)

       {

             Scanner scr = new Scanner(System.in);

             int n = scr.nextInt();

 

             int[] data = new int[n];

             for (int i=0; i<n; i++)

             {

                    data[i] = scr.nextInt();  //read next String in the stream

             }

 

             //process the data array here   

             System.out.println(Arrays.toString(data));

       }

}

SAMPLE EXECUTION

 

4 10 20 30 40

[10, 20, 30, 40]

 

Here is another example mixing int and String inputs.

 

EXAMPLE 2 – AN INTEGER FOLLOWED BY STRINGS

 

The program below deals with input that start with an integer for the value of n.  Then, there are n Strings on the same line all separated by a space.

 

import java.util.Arrays;

import java.util.Scanner;

 

public class InputBasics 

{

       public static void main(String[] args)

       {

             Scanner scr = new Scanner(System.in);

             int n = scr.nextInt();

 

             String[] data = new String[n];

             for (int i=0; i<n; i++)

             {

                    data[i] = scr.next();  //read next String in the stream

             }

 

             //process the data array here   

             System.out.println(Arrays.toString(data));

       }

}

SAMPLE EXECUTION

 

5 blue yellow green red orange

[blue, yellow, green, red, orange]