I'm trying to fill a 2D array of String
values with my own user inputs with Scanner
.
Scanner s = new Scanner(System.in);
String[][] example = new String[20][10];
for (int x = 0; x < example.length; x++) {
System.out.println("Enter name " + (x + 1) + ": ");
example[x] = s.next();
}
I have no issues with filling in [][these ones]
, but I'm having issues with the [these ones]
. I need help with why this doesn't work and what I can do instead to fix it. I'm not super fluent so please try to keep things on the simpler side.
Don't forget you are allowed to use for-loops inside of for-loops. You can use this to your advantage to fill 2D-arrays. For example by using this code:
Scanner s = new Scanner(System.in);
String[][] example = new String[3][3];
for (int i = 0; i < example.length; i++) {
for (int j = 0; j < example[0].length; j++) {
example[i][j] = s.nextLine();
}
}
When you're filling an array using loops you need two (nested) loops - one for the rows and one for the columns (typically in this order).
eg:
for (int row=0; row < twoDArray.length; row++) {
for (int col=0; col < twoDArray[row].length; col++) {
System.out.print("Enter name [" + (row+1) + "][" + (col+1) + "]: ");
twoDArray[row][col] = s.next();
}
}
Row/col are analogous to xy coordinates when drawing a chart.
To extend this further you could do the same for 3D, (and 4D, ... [N]D) arrays by adding a 3rd nested array... the looping would begin to get confusing but its exactly the same principal.
Okay, remember that String[][] is an array of an array of strings. That is, type type of example[0] is String[]. So you have to do a few things. This is the code I wrote:
public class Example {
static int X = 5;
static int Y = 2;
public static void main(String[] args) {
String[][] example = new String[X][Y];
for (int outerIndex = 0; outerIndex < X; ++outerIndex) {
// THIS LINE IS CRITICAL.
example[outerIndex] = new String[Y];
for (int innerIndex = 0; innerIndex < Y; ++innerIndex) {
example[outerIndex][innerIndex] =
new String("("
+ Integer.toString(outerIndex)
+ ","
+ Integer.toString(innerIndex)
+ ")"
);
}
}
for (int outerIndex = 0; outerIndex < X; ++outerIndex) {
for (int innerIndex = 0; innerIndex < Y; ++innerIndex) {
System.out.printf("%s ", example[outerIndex][innerIndex]);
}
System.out.printf("\n");
}
}
}
Output:
$ javac Example.java && java Example
(0,0) (0,1)
(1,0) (1,1)
(2,0) (2,1)
(3,0) (3,1)
(4,0) (4,1)
I didn't want to spew 200 values, so I used a smaller array size.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.