【问题标题】:Java code to calculate number of elements in array用于计算数组中元素数量的 Java 代码
【发布时间】:2023-03-21 03:24:01
【问题描述】:

我有从文件“line.txt”创建 ArrayList 的代码。您能否建议一些方法来获取该 ArrayList 中的元素数量?例如:如果文件有 (43,6,32) 等元素,则输出应为 3(元素数)。

public class scan {
  public static void main(String[] args) throws Exception {

    List<Integer> numbers = new ArrayList<>();
    for (String line : Files.readAllLines(Paths.get("line.txt"))) {
      for (String part : line.split("\\s+")) {
        Integer i = Integer.valueOf(part);
        numbers.add(i);
      }
    }
  }
}

【问题讨论】:

  • numbers.size()?
  • 您应该做的第一件事是检查您感兴趣的类的API。这是ArrayList的API:docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
  • 可能是 numbers.size() 或在搜索 number.next()=null; 时增加整数的方法。无论如何,在arraylist的java API中搜索,有一个方法可以知道整个列表的大小。

标签: java arrays file file-io int


【解决方案1】:

ArrayList 在 docs.oracle 中有自己的 API:

docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

在你的情况下:

public class scan {
public static void main(String[] args) throws Exception {

List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("line.txt"))) {
  for (String part : line.split("\\s+")) {
    Integer i = Integer.valueOf(part);
    numbers.add(i);
  }
}
int answer = number.size();
System.out.println("The number of elements is: " + answer);
}
}

如果你想要另一种方法(但如果你只想知道元素的数量,那就有点愚蠢了)。正在将其转换为数组并按.length 计算数组的元素数,但正如我所说,它有点……长。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2016-05-25
    相关资源
    最近更新 更多