无法从while循环内打印到文本文件

时间:2014-04-30 03:05:00

标签: java while-loop printwriter

所以我在我的程序中想要从csv文件(有两列)中读取的点,在第一列上做一些轻量计算(在我检查它是否有任何内容之后) ),然后将新数字(我从第一个文件中的第1列计算)和第二列的内容从原始文件打印到新的文本文件。

如果没有while循环,我可以毫不费力地对原始文本文件中的数字进行计算,然后将它们打印到新文件中。但是,来自while循环内部的任何打印都会给我一个错误。实际上,除了读取文件并将其解析为字符串数组之外的任何内容都会在while循环中给出错误。

这些是我的stackTrace的前两行,其中包含我目前在下面发布的代码:

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

第476行是我的while循环中的一行:" if(array2 [0] .isEmpty())"

经过几个小时的搜索和修补,我认为是时候寻求帮助了。提前感谢您提供的任何帮助。

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());
}

好的,所以有一些错误。但是根据@ NonSecwitter的建议,我能够把它固定下来。所以第一件事(再次像NonSecwitter提到的那样)我的.csv中有空字段,它抛出了ArrayIndexOutOfBounds"错误。所以我所做的就是用字符串"空"填充.csv中的每个空字段。一旦我这样做,我至少可以打印下一行。

之后,我遇到了另一个错误:这一行:

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

无法通过在if循环内部与前面的read / split语句分开。所以我最终重写了整个while循环的内容,需要像这样抛出一个异常:

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循环中使用PrintWriter有一些限制吗?另外,我非常感谢大家的反馈。我认为,结合所有的意见/建议,我能够确定我的问题在哪里(不是为什么它们是问题)。

感谢!!!

2 个答案:

答案 0 :(得分:1)

如果您提供了样本CSV数据以及<userName>.txt期望的相关输出示例,那将会有所帮助。

如果没有这个,我只能说我的代码没有异常

以下是我在Eclipse中使用从异常输出(分别为finalProyectUser.java)收集的项目和类文件名的快速Java项目所获得的内容,将代码粘贴到类文件中( User.java),并按摩它以进行健全检查......

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();
    }
}

...以及它输出到J0e3gan.txt ...

的示例
finalProyect.User@68a6a21a

        3000                        40      2500.0                        50      4000.0                        25

...使用mealPlan1.csv中的以下(完整WAG)数据:

2000,20
3000,40
2500,50
4000,25

答案 1 :(得分:0)

注释掉有问题的代码并尝试println()array2 [0]并查看它是否为您提供了任何内容。

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]);
    //}
}

或者,尝试打印长度。如果由于某种原因数组为空,则array2 [0]将超出范围

System.out.println(array2.length);

我还会打印line以查看它的内容

System.out.println(line);