gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:50:22 25 4
gpt4 key购买 nike

因此,我在程序中想要从 csv 文件(有两列)中读取内容,对第一列进行一些简单的计算(在检查它是否有任何内容之后),然后打印新数字(我根据第一个文件中的第一列计算得出)和第二列的内容从原始文件到新的文本文件。

如果没有 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” 错误。所以我所做的就是用字符串“empty”填充 .csv 中的每个空字段。一旦我这样做了,我至少能够打印下一行。

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

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

无法通过位于 if 循环内部来与前面的读取/拆分语句分开。因此,我最终重写了整个 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 是否有某些限制?另外,我非常感谢大家的反馈。我认为综合所有评论/建议,我能够确定我的问题出在哪里(只是不是为什么它们是问题)。

谢谢!!!

最佳答案

如果您提供了示例 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

关于java - 无法从 while 循环内打印到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23378960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com