GETTING INPUT
SCENARIO
2A
GETTING n DATA SPACE DELIMITED ON A SINGLE LINE (n is known before run-time)
This is a common situation. In
Java, this is very simple if the data is separated by spaces because the
Scanner methods next(), nextInt() and nextDouble() all recognize spaces in the same was as they
recognize a new line.
SAMPLE INPUT 1 (n = 7)
1 4 4 5 2 4 5
SAMPLE INPUT 2
(n = 4)
4.1
3.4 3.0 1.8
SAMPLE INPUT 3
(n = 3)
apple,orange,banana
|
Here are some examples:
EXAMPLE 1 - INTEGERS
Below is an example where a line of 6 integers separated by a space are
entered as input. So n is 6. We place each integer into its own
element inside an int array named data.
Students sometimes struggle with this because the user
only does data entry once but the Scanner still reads it 6 times. This is because a Scanner only gives the
user an opportunity to enter data if the input stream is empty.
|
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 = 6;
int[] data = new int[n];
for (int i=0; i<n; i++)
{
data[i] = scr.nextInt(); //read
next int in the stream
}
//process the data array here
System.out.println(Arrays.toString(data));
}
}
|
SAMPLE EXECUTION
3 4 5 2 30 4
[3, 4, 5, 2, 30, 4]
|
EXAMPLE 2 –
STRINGS
The following example does the same as the example
above but for an input line of 4 Strings.
So n is 4.
Note that because we want to recognize the space as a
separator, we cannot use scr.nextLine()
here.
|
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 = 4;
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
pat bat rat cat
[pat, bat, rat, cat]
|
EXAMPLE 2B – ALTERNATIVE
OPTION
In this example, our program actually uses scr.nextLine()
to read in the entire line all at once.
This should leave us in a difficult situation because now we have to
separate all the data that is in the line.
However, this easy using the String method split which will
automatically generate a String array for us! Pretty sweet solution!
Note: What is nice about this solution is that it could
work with other forms of delimitation such as data delimited by commas or
dashes.
|
import java.util.Arrays;
import java.util.Scanner;
public class InputBasics
{
public static void main(String[] args)
{
Scanner scr = new Scanner(System.in);
String line = scr.nextLine(); //read entire line
String[] data = line.split(" ");
//process the data array here
System.out.println(Arrays.toString(data));
}
}
|
SAMPLE EXECUTION
dog cat purple
[dog, cat, purple]
|
|