I have this practice Java code that I'm trying to finish. The obvious problem is that when I try to print the array[1][2]
, it returns null, so I'm thinking the array might be empty. How do I take the user input to put in the array?
import java.util.Scanner;
public class Studyone {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int row = 13;
int col = 25;
String sentence;
String sentence2;
String [][] map = new String[row][col];
for (int i = 0; i < map.length; i++)
{
for (int j = 0;i < map.length; i++)
{
System.out.println("Enter the element");
sentence2 = input.nextLine();
map[i][j]=sentence2;
if (row>col)
{
break;
}
}
}
System.out.println(map[1][2]);
}
}
Change
for (int j = 0;i < map.length; i++)
to
for (int j = 0;j < map[0].length; j++)
For example , suppose x = new int[3][4]
, x[0]
, x[1]
, and x[2]
are one-dimensional arrays and each contains four elements, as shown in the figure x.length
is 3
, and x[0].length
, x[1].length
, and x[2].length
are 4
This should help, i think:
for (int i = 0; i < map.length; i++)
{
for (int j = 0;j < map[i].length; j++)
{
System.out.println("Enter the element");
sentence2 = input.nextLine();
map[i][j]=sentence2;
}
}
i
instead of j
in inner loop. map[i].length
condition for inner loop So your inner loop should be
for (int j = 0; j < map[i].length; j++)
^1 ^2 ^3
As first will increment i
twice and for col
you have to consider array of one dimension but you are considering map
which may lead to ArrayIndexOutOfBoundException
.
Here map[i][j]=sentence2;
j
will remain zero
I changed it, but the input just keeps going on and on non-stop.
It will as you have 13 rows and 25 columns so it will take time to insert all the values.So, just change(reduce) size of array and try.
change
for (int j = 0;i < map.length; i++)
to
for (int j = 0;j < map[i].length; j++)
Amend your code to the following:
for (int j = 0;i < map.length; i++)
to
for (int j = 0;i < map[j].length; j++)
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.