首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >DeleteZero使用Java

DeleteZero使用Java
EN

Stack Overflow用户
提问于 2018-10-19 02:53:47
回答 4查看 88关注 0票数 1

我需要完成这段代码,它涉及删除存储在数组中的所有零。我认为它是完整的,但它不能编译,这是我的最后一行是dubios,我没有得到正确的。谢谢。

代码语言:javascript
复制
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));
  }    
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-10-19 03:00:21

错误很少。

这将始终在randi处插入0,因为您正在将Math.random()转换为int,而int将始终变为0。

代码语言:javascript
复制
  rand[i] = (int)(Math.random());

把它改成这样。我已经写了10,但是你可以写任何数字来定义范围。

代码语言:javascript
复制
  rand[i] = (int)(Math.random()*10);

这一行也是错误的:

代码语言:javascript
复制
System.out.println(array(a));

您需要通过循环来打印数组,但更重要的是,您的函数array()返回一个新的数组,该数组应该在打印之前存储在某个地方。

以下是一种可能的解决方法

代码语言:javascript
复制
rand = array(rand);
 for (int i=0; i<rand.length; i++){
     System.out.println(rand[i]);
 }
票数 2
EN

Stack Overflow用户

发布于 2018-10-19 03:14:25

编译时错误是由于在main方法中创建了名为rand的数组并传递了名为a的数组造成的。从main方法调用System.out.print(array(rand))

票数 0
EN

Stack Overflow用户

发布于 2018-10-19 03:03:55

您可以尝试Java8的Stream,它将整个逻辑转换为一行return Arrays.stream(a).filter(n -> n!= 0).toArray();

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52880733

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档