GETTING INPUT
SCENARIO
3A
GETTING n SPACE DELIMITED DATA PER LINE OVER m LINES (n & m are known
before run-time)
If we want to process each line one at a time, then we can simply use the
solution in scenario 4 and place that inside a loop. However, sometimes we need to store all
data in order to process it. In this
case, we will store our data in a 2D array.
SAMPLE INPUT (n = 5, m = 3)
5 3 0 2 1
2 4 5 1 0
9 3 1 5 8
|
Here is an example.
EXAMPLE 1
Below is an example where the program reads in 4 lines of 3 integers and
places all the data into a 2D array.
Note that instead of n, we use rows in the code. And instead of m, we use cols in the
code.
|
import java.util.Arrays;
import java.util.Scanner;
public class InputBasics
{
public static void main(String[] args)
{
Scanner scr = new Scanner(System.in);
int rows = 4; //n
int cols = 3; //m
int[][] grid = new int[rows][cols];
for (int r=0; r<rows; r++)
{
for (int c=0; c<cols; c++)
{
grid[r][c] = scr.nextInt();
}
}
//process the data array here
System.out.println(Arrays.deepToString(grid));
}
}
|
SAMPLE EXECUTION
1 2 3
4 5 6
7 8 9
3 4 5
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 4, 5]]
|
Here is another example with strings.
EXAMPLE 2
Below is an example where the program reads in 3 lines of 2 Strings and
places all the data into a 2D array.
Notice it is very similar to the above example.
|
import java.util.Arrays;
import java.util.Scanner;
public class InputBasics
{
public static void main(String[] args)
{
Scanner scr = new Scanner(System.in);
int rows = 3; //n
int cols = 2; //m
String[][] grid = new String[rows][cols];
for (int r=0; r<rows; r++)
{
for (int c=0; c<cols; c++)
{
grid[r][c] = scr.next();
}
}
//process the data array here
System.out.println(Arrays.deepToString(grid));
}
}
|
SAMPLE EXECUTION
cat bat
mat sat
rat nat
[[cat, bat], [mat, sat], [rat, nat]]
|
|