GETTING
n DATA ON n SEPARATE LINES (n is determined at run-time)
This is a common situation.Often, the first line of entry is the amount of data that has to be
read in.
SAMPLE INPUT 1
4
2
9
5
3
SAMPLE INPUT 2
3
Book
Table
Desk
SAMPLE INPUT 3
0
Here is are a few examples:
EXAMPLE 1
Below is an example where the first number entered represents how much data
there will be.It is very similar to
Example 2 from the previous section with only the 2nd line in
the main function being different.
publicstaticvoid main(String[] args)
{
Scanner scr = new Scanner(System.in);
int n = scr.nextInt();
int[] data = newint[n];
for (inti=0; i<n; i++)
{
data[i] = scr.nextInt();
}
//process the data array here
System.out.println(Arrays.toString(data));
}
And here is another example where we deal with two types of data.
EXAMPLE 2
Below is an example where the user inputs the integer value
of n representing the amount of line in the data.Then, there are n lines of data that are
words (Strings) that have to be read.
We are dealing with two types of data (int and String).So we have to avoid using scr.nextLine().But we can still use scr.next()
to read String.