Question

So I'm at a point in my program where I want to read from a csv file (which has two columns), do some light calculation on the first column (after I check whether or not it has any content), then print the new number (which I calculated from column 1 in the first file) and the contents of the second column from the original file to a new text file.

Without a while loop I have no trouble running calculations on the numbers from the original text file, then printing them to the new file. However ANY printing from inside the while loop is giving me an error. In fact, anything other than reading the file and parsing it into an array of strings is giving me an error from inside the while loop.

These are the top two lines of my stackTrace with the code I currently have posted below:

"Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at finalProyect.User.makeMealPlan(User.java:476)"

Line 476 being the line in my while loop: "if (array2[0].isEmpty())"

After hours of searching and tinkering I thought it was time to ask for help. Thanks in advance for any help you can provide.

public void makeMealPlan() {
    String fileIn = "mealPlan1.csv";
    Scanner inputStream = null;
    String fileOut = userName + ".txt";
    PrintWriter outputStream = null;

    try {
        inputStream = new Scanner(new File(fileIn));//opens and reads pre-configured meal plan
        outputStream = new PrintWriter(fileOut);//creates output file for meal plan
    } catch(FileNotFoundException e3) {
        fileNotFound();
        e3.printStackTrace();
    }
    outputStream.println(toString());
    outputStream.println();
    String line0 = inputStream.nextLine();
    String[] array0 = line0.split(","); //Splits line into an array of strings
    int baseCalories = Integer.parseInt(array0[0]); //converts first item in array to integer
    double caloricMultiplier = (caloricNeeds / baseCalories); //calculates the caloricMultiplier of the user
    String line1 = inputStream.nextLine();//reads the next line
    String[] array1 = line1.split(",");//splits the next line into array of strings
    outputStream.printf("%12s  %24s", array1[0], array1[1]); //prints the read line as column headers into text file
    while(inputStream.hasNextLine()) {
        String line = inputStream.nextLine(); //reads next line
        String[] array2 = line.split(",");
        if(array2[0].isEmpty()) {
            outputStream.printf("%12s  %24s", array2[0], array2[1]);
        } else {

            double quantity = Double.parseDouble(array2[0]);
            quantity = (quantity * caloricMultiplier);
            outputStream.printf("%12s  %24s", quantity, array2[1]);
        }
    }

    outputStream.close();
    System.out.println(toString());
}

Okay, so there were a few things wrong. However with @NonSecwitter's suggestion I was able to pin it down. So first thing (again as NonSecwitter mentioned) I had empty fields in my .csv which was throwing the ArrayIndexOutOfBounds" error. So what I did was I filled every empty field in my .csv with the string "empty". Once I did that I was able to at least print the next line.

After that, I ran into another error which was that this line:

double quantity = Double.parseDouble(array2[0]);

could not be separated from the the preceding read/split statements by being inside of an if-loop. So I ended up rewriting the guts of the entire while-loop and needed to throw an exception like so:

while (inputStream.hasNextLine())
        {
            String[] array2 = null;
            try
            {
            String line = inputStream.nextLine(); //reads next line
            array2 = line.split(",");
            double quantity = Double.parseDouble(array2[0]);
            if (!isStringNumeric(array2[0]))
                throw new NumberFormatException();

            quantity = Math.ceil(quantity * caloricMultiplier);
            outputStream.printf("%12.1f  %15s\n", quantity, array2[1]);
            }
            catch(NumberFormatException e1)
            {
                if (array2[1].equals("empty"))
                    outputStream.printf("%12s  %15s\n", " ", " ");
                else
                    outputStream.printf("%12s %15s\n", " ", array2[1]);
            }

        }

While my program is now currently working just fine, I'd still really appreciate an explanation as to why I ended up having to throw an exception to get the code to work. Are there certain restrictions with using PrintWriter inside of a while-loop? Also, I very much appreciate everybody's feedback. I think with all the comments/suggestions combined I was able to determine where my problems were (just not WHY they were problems).

Thanks!!!

Was it helpful?

Solution 2

Comment out the offending code and try to println() array2[0] and see if it gives you anything.

while (inputStream.hasNextLine())
{
    String line = inputStream.nextLine(); //reads next line
    String[] array2 = line.split(",");
    System.out.println(array2[0]);

    //if (array2[0].isEmpty())
    //   outputStream.printf("%12s  %24s", array2[0], array2[1]);
    //  
    //else
    //{   
    //    
    //    double quantity = Double.parseDouble(array2[0]);
    //    quantity = (quantity * caloricMultiplier);
    //    outputStream.printf("%12s  %24s", quantity, array2[1]);
    //}
}

or, try to print the length. If the array were empty for some reason array2[0] would be out of bounds

System.out.println(array2.length);

I would also print line to see what it's picking up

System.out.println(line);

OTHER TIPS

It would help if you provided sample CSV data and an example of the related output you expect in <userName>.txt.

Short of this I can only help insofar as saying I do not get an exception with your code.

Here is what I got with a quick Java project in Eclipse using project and class-file names gleaned from your exception output (finalProyect and User.java respectively), pasting your code into the class file (User.java), and massaging it a bit for a sanity check...

package finalProyect;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class User {
    public void makeMealPlan()
    {
        String fileIn = "C:\\Temp\\mealPlan1.csv";//"mealPlan1.csv"; // FORNOW: adjusted to debug
        Scanner inputStream = null;
        String userName = "J0e3gan"; // FORNOW: added to debug
        String fileOut = "C:\\Temp\\" + userName  + ".txt"; // FORNOW: adjusted to debug
        PrintWriter outputStream = null;

        try
        {
            inputStream = new Scanner(new File(fileIn));//opens and reads pre-configured meal plan
            outputStream = new PrintWriter(fileOut);//creates output file for meal plan
        }   
        catch(FileNotFoundException e3)
        {
            //fileNotFound(); // FORNOW: commented out to debug
            e3.printStackTrace();
        }
        outputStream.println(toString());
        outputStream.println();
        String line0 = inputStream.nextLine();
        String[] array0 = line0.split(","); //Splits line into an array of strings
        int baseCalories = Integer.parseInt(array0[0]); //converts first item in array to integer
        int caloricNeeds = 2000; // added to debug
        double caloricMultiplier = (caloricNeeds  / baseCalories); //calculates the caloricMultiplier of the user
        String line1 = inputStream.nextLine();//reads the next line
        String[] array1 = line1.split(",");//splits the next line into array of strings
        outputStream.printf("%12s  %24s", array1[0], array1[1]); //prints the read line as column headers into text file
        while (inputStream.hasNextLine())
        {
            String line = inputStream.nextLine(); //reads next line
            String[] array2 = line.split(",");
            if (array2[0].isEmpty())
                outputStream.printf("%12s  %24s", array2[0], array2[1]);

            else
            {   

                double quantity = Double.parseDouble(array2[0]);
                quantity = (quantity * caloricMultiplier);
                outputStream.printf("%12s  %24s", quantity, array2[1]);
            }
        }

        outputStream.close();
        System.out.println(toString());
    }

    public static void main(String[] args) {
        // FORNOW: to debug
        User u = new User();
        u.makeMealPlan();
    }
}

...and an example of what it output to J0e3gan.txt...

finalProyect.User@68a6a21a

        3000                        40      2500.0                        50      4000.0                        25

...with the following (complete-WAG) data in mealPlan1.csv:

2000,20
3000,40
2500,50
4000,25
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top