简体   繁体   English

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

[英]Cannot print to text file from within while-loop

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. 所以我到了程序中要从csv文件(具有两列)读取的位置,对第一列进行了一些轻度的计算(在我检查它是否有任何内容之后),然后打印新编号(我从第一个文件的第1列计算得出),第二列的内容从原始文件到新的文本文件。

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. 没有while循环,我可以毫不费力地对原始文本文件中的数字进行计算,然后将其打印到新文件中。 However ANY printing from inside the while loop is giving me an error. 但是,从while循环内部进行的任何打印都给我一个错误。 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. 实际上,除了读取文件并将其解析为字符串数组之外,其他任何事情都从while循环内部给我一个错误。

These are the top two lines of my stackTrace with the code I currently have posted below: 这是我stackTrace的最上面两行,下面是我当前发布的代码:

"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())" 第476行是我的while循环中的行:“ 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. 但是,通过@NonSecwitter的建议,我可以将其固定下来。 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. 因此,第一件事(再次如NonSecwitter所述),我的.csv中有空字段,这引发了ArrayIndexOutOfBounds“错误。所以我要做的是用字符串” empty“填充.csv中的每个空字段。我至少能够打印下一行。

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. 不能通过if循环与前面的read / split语句分开。 So I ended up rewriting the guts of the entire while-loop and needed to throw an exception like so: 因此,我最终重写了整个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 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? 在while循环内使用PrintWriter是否有某些限制? 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!!! 谢谢!!!

It would help if you provided sample CSV data and an example of the related output you expect in <userName>.txt . 如果您在<userName>.txt提供了示例CSV数据示例和相关输出示例,这将有所帮助。

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... 这是我在Eclipse中使用快速Java项目得到的结果,该项目使用从异常输出(分别为finalProyectUser.java )收集的项目和类文件名,将代码粘贴到类文件( User.java )中,并对其进行finalProyect进行健全性检查...

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 ... ...以及输出到J0e3gan.txt ...

finalProyect.User@68a6a21a

        3000                        40      2500.0                        50      4000.0                        25

...with the following (complete-WAG) data in mealPlan1.csv : ...在mealPlan1.csv具有以下(完全WAG)数据:

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

Comment out the offending code and try to println() array2[0] and see if it gives you anything. 注释掉有问题的代码,然后尝试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]);
    //}
}

or, try to print the length. 或者,尝试打印长度。 If the array were empty for some reason array2[0] would be out of bounds 如果由于某种原因数组为空,则array2 [0]将超出范围

System.out.println(array2.length);

I would also print line to see what it's picking up 我也将打印line以查看其内容

System.out.println(line);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM