gpt4 book ai didi

java - 摆脱二维 Java 数组中的自动填充零

转载 作者:行者123 更新时间:2023-12-02 03:46:21 25 4
gpt4 key购买 nike

用户输入的数字每行最多 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;
}
}

最佳答案

您应该查看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);
}
}

关于java - 摆脱二维 Java 数组中的自动填充零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36269396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com