簡體   English   中英

Java 2D數組學習

[英]Java 2D Array learn

我已經嘗試完成此練習Java代碼。 明顯的問題是,當我嘗試打印array[1][2] ,它返回null,因此我認為該數組可能為空。 我如何將用戶輸入放入數組中?

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]);
    }
}

更改

for (int j = 0;i < map.length; i++) 

for (int j = 0;j < map[0].length; j++) 

例如 ,假設x = new int[3][4] x[0] x[1]x[2]是一維數組,並且每個包含四個元件,如該圖所示x.length3x[0].lengthx[1].lengthx[2].length4

在此處輸入圖片說明

我認為這應該有所幫助:

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而不是內部循環中的j條件。
  • 使用map[i].length條件進行內循環

所以你的內循環應該是

for (int j = 0; j < map[i].length; j++)
                ^1      ^2         ^3

因為首先將使i增加兩次,對於col您必須考慮一個維的數組,但是您正在考慮可能導致ArrayIndexOutOfBoundException map

這里map[i][j]=sentence2; j將保持為零

我更改了它,但是輸入只是一直不停地進行。

您將擁有13行25列,因此插入所有值將花費一些時間。因此,只需更改(減小)數組的大小並嘗試。

更改

for (int j = 0;i < map.length; i++)

for (int j = 0;j < map[i].length; j++)

將您的代碼修改為以下內容:

for (int j = 0;i < map.length; i++)

for (int j = 0;i < map[j].length; j++)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM