数组中的一组数字(对象)



我对Java很陌生,这是我第一个无法独自解决的问题。我如何处理来自Object方法的数字?我想把所有得到的数字都放进一个数组,但怎么做呢?如果有人能帮助我,我会很高兴的!

int close = 0; while(close < 301){ close++;
DataFormatter formatter = new DataFormatter();
formatter.formatCellValue(sheet.getRow(close).getCell(4));

考虑使用Java 8 Stream API执行此任务。你可以创建这样的方法:

private String [] getCellValues(int start, int end, int cellIndex, Sheet sheet){
DataFormatter formatter = new DataFormatter(); //1
return IntStream.range(start,end) //2
.mapToObj(sheet::getRow) //3
.map(row->row.getCell(cellIndex)) //4
.map(formatter::formatCellValue) //5
.toArray(String[]::new); //6
}

现在让我们更详细地介绍每一行代码:

  1. 创建新的DataFormatter
  2. 创建从开始(包括(到结束(不包括(的整数范围。在你的情况下,这将是数字1、2、3…300
  3. 在工作表上应用方法getRow(),每个数字作为参数并返回Row对象的流
  4. 在每个Row对象上应用方法getCell(4),这样就得到了一个Cell对象流
  5. DataFormatter方法formatCellValue应用于每个小区,返回String的流
  6. 将所有的Strings收集到像String[]一样的数组中(考虑使用collect(collectors.toList()),因为List更方便(

2行中的return语句全部返回结果。如果需要将String值转换为intlong,则应在第5行和第6行之间添加.map(Integer::parseInt).map(Long::parseLong),然后分别更改第6行。

如果你更熟悉循环,你可以使用这样的东西:

private String[] getCellValues(int start, int end, int cellIndex, Sheet sheet) {
DataFormatter formatter = new DataFormatter();
int arraySize = end - start - 1;
String[] cellValues = new String[arraySize];
for (int i = start; i < end; i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(cellIndex);
String cellValue = formatter.formatCellValue(cell);
cellValues[i] = cellValue;
}
return cellValues;
}

但如果可能的话,也可以考虑使用List而不是数组。

最新更新