简体   繁体   English

Java 2D数组学习

[英]Java 2D Array learn

I have this practice Java code that I'm trying to finish. 我已经尝试完成此练习Java代码。 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. 明显的问题是,当我尝试打印array[1][2] ,它返回null,因此我认为该数组可能为空。 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 例如 ,假设x = new int[3][4] x[0] x[1]x[2]是一维数组,并且每个包含四个元件,如该图所示x.length3x[0].lengthx[1].lengthx[2].length4

在此处输入图片说明

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;
     }
}
  • You are incrementing and checking condition for i instead of j in inner loop. 您正在递增并检查i而不是内部循环中的j条件。
  • Use map[i].length condition for inner loop 使用map[i].length条件进行内循环

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 . 因为首先将使i增加两次,对于col您必须考虑一个维的数组,但是您正在考虑可能导致ArrayIndexOutOfBoundException map

Here map[i][j]=sentence2; 这里map[i][j]=sentence2; j will remain zero j将保持为零

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. 您将拥有13行25列,因此插入所有值将花费一些时间。因此,只需更改(减小)数组的大小并尝试。

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++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM