如何使用 java 在 Excel sheet 的列中找到最大值?

How to find maximum value in a column of an Excel sheet using java?

The image displays my dataset

我想在第一列中找到最大值,但是下面的代码显示错误。

Bus1.java:52: error: bad operand types for binary operator '>=' if(numbusarray.get(row)>=max); ^ first type: String second type: int Bus1.java:53: error: incompatible types: String cannot be converted to int max=numbusarray.get(row);

import java.io.FileInputStream;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import java.io.*;
import java.util.*;

public class Bus1{

List<String> numbusarray = new ArrayList<String>();
List<String> numcommutersarray = new ArrayList<String>();
List<String> numcommercialarray = new ArrayList<String>();

public void readExcel() throws BiffException, IOException//method to read       contents form excel
{
    String FilePath = "Bus1.xls";
    Scanner sc = new Scanner(System.in);
    int max=0;

    FileInputStream fs = new FileInputStream(FilePath);
    Workbook wb = Workbook.getWorkbook(fs);
    Sheet sh = wb.getSheet("Bus1");// TO get the access to the sheet
    int totalNoOfRows = sh.getRows();// To get the number of rows present in  sheet
    int totalNoOfCols = sh.getColumns();// To get the number of columns present in sheet

    //adding excel contents from every column to arraylist

    for (int row = 1; row < totalNoOfRows; row++)
    {
        numcommutersarray.add(sh.getCell(3, row).getContents());
    }

    for (int row = 1; row < totalNoOfRows; row++)
    {
        numcommercialarray.add(sh.getCell(5, row).getContents());
    }

    for (int row = 1; row < totalNoOfRows; row++)
    {
        if(numbusarray.get(row)>=max);
        max=numbusarray.get(row);

    }
    System.out.println(max);

    Iterator itr=numbusarray.iterator(); //to print arraylist demo 
    while(itr.hasNext()){  
        System.out.println(itr.next());  
    }
    }//end of method to read contents from excel

    public static void main(String args[]) throws BiffException, IOException  //main class
    {
        Bus1 DT = new Bus1();
        DT.readExcel();
    }//end of main class

}

您的 numbusarray 包含字符串,您正试图将 stringint 进行比较。您应该首先像这样转换为 int:

int intNumber = Integer.parseInt(YourString);

并且始终确保您的 String 可以转换为 int 否则它会引发 NumberFormatException,您还可以输出您的 numbusarray 内容检查。

虽然有时Java可以帮助你转换类型,但对于初学者来说,显式转换类型更好,我相信这会节省你很多时间。

要向 List 添加内容,您应该将适当类型的对象放入其中。这就是你的

List<String> numcommutersarray

想要,它包含String类型的对象。