簡體   English   中英

如何使用Java在Excel工作表的列中找到最大值?

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

該圖像顯示了我的數據集

我想在第一列中找到最大值,但是下面的代碼顯示錯誤。

Bus1.java:52:錯誤:二進制運算符'> ='的錯誤操作數類型if(numbusarray.get(row)> = max); ^第一種類型:字符串第二種類型:int Bus1.java:53:錯誤:不兼容的類型:字符串不能轉換為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類型的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM