I want to find the maximum value in the first column, but the code below shows an error.
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
}
Your numbusarray contains strings and you are trying to compare string with int. You should first convert to int like this:
int intNumber = Integer.parseInt(YourString);
And always make sure your String can be converted to int otherwise it will raise a NumberFormatException, you can also output your numbusarray contents to check.
Although sometimes Java can help you convert types but for beginners it's better to explicitly convert types and I believe this will save you a lot of time.
For adding things to List, you should put the appropriate type objects into it. That's what your
List<String> numcommutersarray
wants, it contains the String type objects.