0

I am trying to read a comma-separated value file but I can't seem to get my code to work. Any clue where my code is incorrect?

Notes: Trying to read only the Price column and make sure the values are not NULL, N/A, less than 80 and greater than 130.

SpreadSheet:

SPreadsheet

boolean flag = true; 
File inputF = new File("data.csv")
InputStream getStream = new FileInputStream(inputF);

try{
    if(getStream.read() != -1){
    BufferedReader reader = new BufferedReader(new InputStreamReader(getStream));
    String line;

    while((line = reader.readLine()) != null){
        String[] csvs = line.split(",");
        for (String str : csvs){
            if (str != null && (str.equals("NA") || str.length() == 0)) {
                System.out.println(str);
                flag = false;
                break;
            }
        }
        if (!flag){
            break;
        }else{
            String Price = csvs[1]; 
            price = price.trim();
            Integer priceValue = new Integer(Price); //exception occurs here 
            if (priceValue != null && (priceValue < 80 || priceValue > 130)){
                flag = true;
            }
        }
    }
    reader.close();
    }
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(flag);
return flag;

Error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "PRICE" 

Expected Output: (Based on spreadsheet provided)

True 
JoshDM
  • 4,939
  • 7
  • 43
  • 72
BigO
  • 334
  • 1
  • 3
  • 16
  • From a quick Look: Are you trying to parse the headlines into Integers by any chance? (The first line that contains "Date, Product, Price" - that you obviously would want to skip when parsing the data) – OH GOD SPIDERS Sep 04 '20 at 14:41
  • Side note: a `.csv` file is not an Excel (.xls or .xlsx) file. It is a "comma separated values" file. – 001 Sep 04 '20 at 14:44

2 Answers2

4

I am trying to read an Excel file ....

The code ... and the output ... indicates that you are actually trying to parse a CSV file, not an Excel file.

The exception message is this:

Exception in thread "main" java.lang.NumberFormatException:
     For input string: "PRICE"

The error message is telling. That "PRICE" string is coming from the first line of your CSV file. The solution is simple. Read and discard the first line of the file; i.e. the line that contains column names not data.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

The error is given for the first line on "PRICE." Check for digits only:

    String price = csvs[1].trim();
    if (price.matches("-?\\d+")) { // Possibly negative integer.
        int priceValue = Integer.parseInt(Price);
        if (priceValue < 80 || priceValue > 130){
            flag = true;
        }
    }
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138