我需要完成这段代码,它涉及删除存储在数组中的所有零。我认为它是完整的,但它不能编译,这是我的最后一行是dubios,我没有得到正确的。谢谢。
public class DeleteZero {
public static int[] array(int[] a) {
int k = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] !=0)
k++;
}
int[] b = new int[k];
int t = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
b[t] = a[i];
t++;
}
}
return b;
}
public static void main (String args[]) {
int[] rand = new int[20];
for (int i = 0; i < 20; i++) {
rand[i] = (int)(Math.random());
}
System.out.println(array(a));
}
}
发布于 2018-10-19 03:00:21
错误很少。
这将始终在randi处插入0,因为您正在将Math.random()转换为int,而int将始终变为0。
rand[i] = (int)(Math.random());
把它改成这样。我已经写了10,但是你可以写任何数字来定义范围。
rand[i] = (int)(Math.random()*10);
这一行也是错误的:
System.out.println(array(a));
您需要通过循环来打印数组,但更重要的是,您的函数array()返回一个新的数组,该数组应该在打印之前存储在某个地方。
以下是一种可能的解决方法
rand = array(rand);
for (int i=0; i<rand.length; i++){
System.out.println(rand[i]);
}
发布于 2018-10-19 03:14:25
编译时错误是由于在main方法中创建了名为rand
的数组并传递了名为a
的数组造成的。从main方法调用System.out.print(array(rand))
发布于 2018-10-19 03:03:55
您可以尝试Java8的Stream,它将整个逻辑转换为一行return Arrays.stream(a).filter(n -> n!= 0).toArray();
https://stackoverflow.com/questions/52880733
复制相似问题