gpt4 book ai didi

java - 从二维数组中顺序接收元素(Java)

转载 作者:搜寻专家 更新时间:2023-11-01 02:58:58 26 4
gpt4 key购买 nike

我是 Java 初学者,我需要编写一个 next() 方法,该方法将从二维数组返回当前值。

例如,我们可能有:

int[][] values = {{1, 2}, {3, 4}, {5, 6}}; 

当我们第一次使用 next() 时,它返回 1,第二次使用 - 2,第三次 - 3

我的解决方案是从该二维数组制作一维数组:

 public int[] convert(int[][] array) {

// At first, count number of all cells to set length for new 1D array.

int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
count++;
}
}

// Now we have length. Creating new array and filling it with data from all arrays.

int[] result = new int[count];
int index = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
result[index] = array[i][j];
index++;
}
}
return result;
}

然后从那个新的一维数组中获取一个值(position 是一个类字段= 0values 也是一个类字段- int[][] 值):

public int next() {
int[] tmp = convert(values);
int result = tmp[position];
position++;
return result;
}

但是很明显这个方案不是最好的。有没有办法在没有阵列对话的情况下做到这一点?

类似Iterator的next()hasNext()的方法吗?

更新。我写了一些错误的代码来说明我想做什么:

public class ArrayConverter {
private final int[][] values;
private int upper = 0;
private int lower = -1;

public ArrayConverter(int[][] values) {
this.values = values;
}

public int next() {
lower++;
int result = 0;
try {
result = values[upper][lower];
} catch (ArrayIndexOutOfBoundsException a) {
lower = 0;
upper++;
try {
result = values[upper][lower];
} catch (ArrayIndexOutOfBoundsException r) {
upper = 0;
lower = -1;
System.out.print("Reached the end of data. Indexes will be zeroed.");
}
}
return result;
}
}

由于 try/catch block ,该代码很糟糕,我宁愿避免它。怎么办?

最佳答案

如果您使用List,那么您将避免计算元素的数量:

int[][] array = {{1, 2}, {3, 4}, {5, 6}}; 
List<Integer> list = new ArrayList<>();
for (int[] array1 : array) {
for (int j = 0; j < array1.length; j++) {
list.add(array1[j]);
}
}

然后您可以使用 list.get(position);

获取您的值

关于java - 从二维数组中顺序接收元素(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41964840/

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