GETTING INPUT
SCENARIO
1A
GETTING n DATA ON n SEPARATE LINES (n is known before run-time)
This is the easiest situation (as it resembles what you’ve likely done in
class). You know how many lines to
read and you simply associate a variable with each line. So you end up with n variables or values.
SAMPLE INPUT 1 (We know beforehand
that n is 5)
3
4
9
2
8
SAMPLE INPUT 2
(We know beforehand that n is 6.)
Bear
Lion
Dog
Giraffe
Rat
Deer
|
Here are examples of this type of scenario.
EXAMPLE 1
Below is an example where we get four integers from the user before
processing it. Note that this type
of solution does not work well if there are many values to input (like 20)
as you need to create that many variables.
|
public static void main(String[] args)
{
Scanner scr = new Scanner(System.in);
int firstData = scr.nextInt();
int secondData = scr.nextInt();
int thirdData = scr.nextInt();
int fourthData = scr.nextInt();
//process data here
}
|
If we do not need to store the data, then we can just use a loop.
EXAMPLE 2
Below is an example where you are asked to output the
sum of twelve provided numbers. So n
is 12. Since we can tally up the sum
as we go, we do not need to store each value individually.
|
public static void main(String[] args)
{
Scanner scr = new Scanner(System.in);
int n = 12;
int total = 0;
for (int i=0; i<n; i++)
{
total += scr.nextInt();
}
System.out.println(total);
}
|
If we do need to store the data for processing later on and n is
large enough, then we will want to use an array.
EXAMPLE 3
Below is an example where we need to get 20 double values. So n is 20. We could use the approach from above and
that would work but an array will be more time efficient. This becomes even more true for larger amounts of values.
|
public static void main(String[] args)
{
Scanner scr = new Scanner(System.in);
int n = 20;
double[] data = new double[n];
for (int i=0; i<n; i++)
{
data[i] = scr.nextDouble();
}
//process the data array here
}
|
|