在2d Java数组中摆脱自动填充的零

时间:2016-03-28 19:14:33

标签: java arrays

用户输入的数字最多为每行20行和50行。问题是如果用户在一行上输入少于20个整数,则数组在空格中填充零,以便总共有20个。这会影响我使用数组完成的计算。

有没有人知道摆脱这些零的有效方法,以便只保留原始输入的数字?

//Extracting/reading from file
public void readFile(File file) {

    try {
        //creates scanner to read file
        Scanner scn = new Scanner(file);

        //set initial count (of rows) to zero
        int maxrows = 0;

        //sets columns to 20 (every row has 20 integers - filled w zeros if not 20 inputted)
        int maxcolumns = 20;

        // goes through file and counts number of rows to set array parameter for length
        while (scn.hasNextLine()) {
            maxrows++;
            scn.nextLine();
        }

        // create array of counted size
        int[][] array = new int[maxrows][maxcolumns];

        //new scanner to reset (read file from beginning again)
        Scanner scn2 = new Scanner(file);

        //places integers one by one into array
        for (int row = 0; row < maxrows; row++) {
            Scanner lineScan = new Scanner(scn2.nextLine());
            //checks if row has integers
            if (lineScan.hasNextInt()) {

                for (int column = 0; lineScan.hasNextInt(); column++) {
                    array[row][column] = Integer.parseInt(lineScan.next());
                }

            } else System.out.println("ERROR: Row " + (row + 1) + " has no integers.");
        }
        rawData = array;
    }
}

4 个答案:

答案 0 :(得分:2)

您应该查看List。由于您承认您不知道要插入多少元素,因此我们可以根据用户想要添加的许多内容简单地扩展列表。

// Initialize the initial capacity of your dataMatrix to "maxRows",
// which is NOT a hard restriction on the size of the list
List<List<Integer>> dataMatrix = new ArrayList<>(maxrows);

// When you want to add new elements to that, you must create a new `List` first...

for (int row = 0 ; row < maxrows ; row++) {
    if (lineScan.hasNextInt()) {
        List<Integer> matrixRow = new ArrayList<>();
        for (int column = 0; lineScan.hasNextInt(); column++) {
            dataMatrix.add(Integer.parseInt(lineScan.next()));
        }
        // ...then add the list to your dataMatrix.
        dataMatrix.add(matrixRow);
    }
}

答案 1 :(得分:0)

如Java labguage Specifications中所述,数组的所有元素都将使用&#39; 0&#39;来初始化。如果数组类型为int,则为value。

但是,如果要区分用户输入的0和默认分配的0,我建议使用Integer类的数组,以便所有值使用null初始化,尽管需要在代码中进行更改(即在null字面值中转换之前检查int值),例如:

Integer[][] array = new Integer[maxrows][maxcolumns];

答案 2 :(得分:0)

在这种情况下,您可以创建ArrayList的ArrayList而不是2d Arrays。

ArrayList<ArrayList<Integer>> group = new ArrayList<ArrayList<Integer>>(maxrows);

现在,您可以根据输入值动态分配值,因此如果数据连续包含少于20个,则不会向数据添加额外的零。

答案 3 :(得分:0)

当我需要不同数量的整数时,我通常会使用ArrayList<Integer>

如果必须有数组,则将所有内容设置为-1(如果-1是无效/前哨输入),或者计算用户输入数字的次数。然后你只需要在达到-1或超过输入数量时停止。

相关问题