简体   繁体   English

如何在Java中获取二维动态数组的输入?

[英]How to take inputs for 2 Dimensional dynamic array in Java?

I am writing a code where inputs will be taken from the user and stored in a 2-Dimensional dynamic array. 我正在编写一个代码,其中输入将从用户那里获取并存储在二维动态数组中。 We know the no. 我们知道没有。 of rows of the array. 数组的行数。 But the number of columns of the array is dynamic. 但是数组的列数是动态的。

The input will be in the form as shown below: 输入将采用如下所示的形式:

3 3

sghjhlklj sghjhlklj

ghgh ghgh

ytyhuj ytyhuj

Since 3 is entered first, there would be three subsequent strings which have to be stored in an array. 由于首先输入3,因此必须将三个后续字符串存储在数组中。

Following is the code snippet that I have written. 以下是我编写的代码段。 But it shows array index out of bounds exception. 但是它显示了数组索引超出范围的异常。

import java.util.Arrays;
import java.util.Scanner;

class Main
{
    // Read a String from the standard input using Scanner
    public static void main(String[] args)
    {

        Scanner in = new Scanner(System.in); 

        Integer no = in.nextInt(); 
        System.out.println("You entered string "+no); 
        int z = 0,y=0 ;

        char[][] arr = new char[no][];

        for(z=0 ; z<no ; z++)
        {
            String s = in.nextLine(); 
            String[] arrOfStr = s.split("");
            for( y =0 ; y<arrOfStr.length ; y++)
            {
                arr[z][y]=arrOfStr[y].charAt(0);

            }



        }     


        in.close();     
    }
}

You have 3 issues with your code: 您的代码有3个问题:

  1. You never initialize the inner arrays. 您永远不会初始化内部数组。 Do it with arr[z] = new char[s.length()]; arr[z] = new char[s.length()]; .
  2. The way you define arrOfStr . 定义arrOfStr的方式。 You split the string by the blank sub-string. 您将字符串除以空白子字符串。 Instead just use s use charAt like this: arr[z][y] = s.charAt(y); 相反,仅使用s可以这样使用charAtarr[z][y] = s.charAt(y);
  3. As the comments suggested, there is the issue with nextInt that does not take into account the \\n (enter) char. 如注释所建议, nextInt存在一个问题,该问题未考虑\\n (输入)字符。 So use int no=Integer.parseInt(in.nextLine()); 所以使用int no=Integer.parseInt(in.nextLine()); , instead of using nextInt . ,而不是使用nextInt

The final code should look like this: 最终代码应如下所示:

for(z=0 ; z<no ; z++)
{
    String s = in.nextLine(); 
    arr[z] = new char[s.length()];
    for( y =0 ; y<s.length() ; y++)
    {
        arr[z][y]=s.charAt(y);
    }
}   

In java 2D array is initially 1D array of arrays . java 2D数组最初是1D array of arrays This is not C++ : 这不是C++

  • You have to know the number of rows only; 您只需要知道行数即可。
  • Each sub-array (a line) could have a different length. 每个子数组(一行)的长度可能不同。

String[][] matrix = new String[3][]; // declare an 2D array with 3 rows and not define column length
matrix[0] = new String[5]; // 1st line has 5 columns; matrix[0][4] is the last column of 1st row
matrix[1] = new String[10]; // 2nd line has 10 columns; matrix[1][9] is the last column of 2nd row
// matrix[2] == null -> true // 3rd line is not initialized

String[][] matrix = new String[2][2]; // declare 2D array and initialize all rows with 1D sub-array with 2 columns (i.e. we have a square).

Try this code: 试试这个代码:

The first problem was you did not initalize the inner array. 第一个问题是您没有初始化内部数组。 Furthermore you used both nextInt() and nextLine() . 此外,您同时使用了nextInt()nextLine() The nextInt() method does not take into account your \\n (newLine symbol) . nextInt()方法未考虑您的\\n (newLine符号)。 So the nextLine() method will directly consume it and does not take into account your subsequent input. 因此, nextLine()方法将直接使用它,而不考虑您的后续输入。

public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
            Integer no;
            do { // this is some flaky code but it works for this purpose
                try {
                    no = Integer.parseInt(in.nextLine());
                    break;
                } catch (Exception e) {
                    System.out.println("please enter only a numeric value");
                }
            } while (true);

            System.out.println("You entered string " + no);
            int z = 0, y = 0;

            char[][] arr = new char[no][];

            for (z = 0; z < no; z++) {
                String s = in.nextLine();
                String[] arrOfStr = s.split("");
                arr[z] = new char[arrOfStr.length];
                for (y = 0; y < arrOfStr.length; y++) {
                    System.out.println();
                    arr[z][y] = arrOfStr[y].charAt(0);
                }
            }
            for (char[] charArr : arr) {
                for (char c : charArr) {
                    System.out.println(c);
                }
            }
        }
    }

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

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