【问题标题】:Removing all zeros from an array list?从数组列表中删除所有零?
【发布时间】:2014-04-01 00:35:09
【问题描述】:

所以我目前有:

List<String> lineList = new ArrayList<String>();
String thisLine = reader.readLine();

while (thisLine != null) {
    lineList.add(thisLine);
    thisLine = reader.readLine();
}
System.out.println(lineList);

这基本上是读取文本文件并返回文本文件中的数字。 我得到的输出是[0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0] 这似乎是正确的。但是我要做的是在不创建新数组的情况下删除所有零。但是我是否必须将此字符串 arraylist 转换为整数数组列表才能这样做?我怎么能只删除零? 谢谢!

【问题讨论】:

  • 每行是否只有一个整数?
  • 不会再循环使用lineList 解决lineList.remove() 的问题?
  • 去掉“0”或者0是一样的

标签: java arrays file-io arraylist


【解决方案1】:

你只需要像这样修改你的while循环:

 while (thisLine != null) {
       if(!thisLine.trim().equals("0")) {
           lineList.add(thisLine);
       }
        thisLine = reader.readLine();
    }

编辑:

根据您输入的上述代码将不起作用,因为您将所有内容都放在一行中。您应该使用 Scanner 来读取它:

Scanner s = new Scanner(new File(<your file path>));
 List<Integer> lineList = new ArrayList<Integer>();

while(s.hasNextInt()){
    int i = s.nextInt();
     if(i!=0) {
         lineList.add(i);
     }
}

希望这会有所帮助。

【讨论】:

  • 我喜欢这个解决方案,因为它避免了首先添加 0。
  • 我用它替换了我的while循环,但是当我输出lineList时它仍然给我一个带有零的列表,知道为什么吗?
  • 文件内容是什么?
  • 正是这个“0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0”
  • 啊,它成功了!非常感谢!熬夜试图解决这个程序。
【解决方案2】:

我会在 while 循环中使用它:

while (thisLine != null) {
    if(!thisLine.equals("0"){
        lineList.add(thisLine);
    }
    thisLine = reader.readLine();
}

【讨论】:

    【解决方案3】:

    大概这样就足够了?

    for(Iterator<String> it=lineList.iterator(); it.hasNext();) {
        String str = it.next();
        if(str.equalsIgnoreCase("0")) {
            it.remove();   
        }
    }
    

    【讨论】:

      【解决方案4】:

      使用 removeAll() 方法从 ArrayList 中删除所有零...

      lineList.removeAll(Collections.singleton(0));

      【讨论】:

        猜你喜欢
        • 2019-02-14
        • 2019-11-24
        • 2019-12-09
        • 2015-04-02
        • 2015-03-05
        • 2020-07-17
        • 2023-03-10
        相关资源
        最近更新 更多