System.out.println()如何在java中工作?

在下面提到的代码中,我试图从Excel工作表中获取数据并将其存储在数组中。 我已经写了代码来从我的ReadExcelData方法中的Excel文件中获取数据。 现在,我面临的问题是我的主要方法,当我通过使用数组打印数据数据打印多次。 我发现,因为我已经使用System.out.println()里面的两个lop这就是为什么它被打印多次。 为了解决这个问题,我删除了System.out.println()(注释 – 在下面的代码中,粗体System.out.println()是我从ReadExcelData方法中删除的),一旦我做了,我无法得到任何输出。 请告诉我如何才能从ReadExcelData获取数据,而不打印它,因为我想在主要方法中打印数据。

package com.selenium; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.*; @SuppressWarnings("unused") public class ReadExcelData { static String[] data = new String[15]; public String getData() throws InvalidFormatException, IOException{ String data="Initial"; File file = new File("C:\\Users\\Admin\\Desktop\\ScreenShot\\Excel.xls"); FileInputStream input = new FileInputStream(file); Workbook work = WorkbookFactory.create(input); Sheet sheet = work.getSheet("Data"); int rownum=sheet.getLastRowNum(); //System.out.println("Row number = "+rownum); for(int i=0;i<rownum+1; i++){ Row row=sheet.getRow(i); if(row != null){ for(int j=0; j<row.getLastCellNum();j++){ //System.out.println(row.getLastCellNum()); if(row.getCell(j) != null){ data = row.getCell(j).getStringCellValue(); if(data != null){ **System.out.println(data);** }//if2 }//if1 }//for2 }//if3 }//for1 return data; }//getdata public static void main(String[] args) throws InvalidFormatException, IOException{ ReadExcelData read =new ReadExcelData(); for(int i=0;i<data.length;i++){ data[i]= read.getData(); } }//main }//class Code block which is giving problem- if(data != null){ **System.out.println(data);** }//if2 

你正在循环调用你的方法:

  for(int i=0;i<data.length;i++){ data[i]= read.getData(); } 

所以它是多次打印。

如果你想把所有的值都放在数据中,那么你应该做下面的改变

 public String[] getData() throws InvalidFormatException, IOException{ String[] data = new String[15]; ... int k =0; ... String cellVal = row.getCell(j).getStringCellValue(); if(cellVal != null){ data[k++] = cellVal; }//if2 .... return data; } 

从main方法调用它只有一次:

 String[] excelData = read.getData(); 

问题是,对于您的对象数据的每个单元格,您正在调用填充它的方法。 你有:

  data[i]= read.getData(); 

然后你有15次的方法,打开,阅读和返回整个文件15次。

只要从你的主要删除循环,一切都会按照你的想法。