在尝试向文件读取、执行计算以及从文件输出数据时出现编译错误



我试图从一个文件中读取数据,将数据输出到另一个文件,并使用输入文件中的数据进行计算并输出。我正在尝试使用StringTokenizer来获取文本文件的数字,我以前从未使用过。这是我迄今为止的代码。

import java.io.*;
import java.util.*;
public class project3
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
BufferedReader br = new BufferedReader(new FileReader("d:/Data/Project3.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("d:/Data/Project3OutData.txt"));
String str;
double tax;
double total;
double payment;
double rent;
System.out.println("Enter the interest rate: ");
double intRate = scan.nextDouble();
System.out.println("Enter months for the loan: ");
int months = scan.nextInt();
try
{
while ((str = br.readLine ()) != null)  
{
StringTokenizer st1 = new StringTokenizer(str);
String name = st1.nextToken();
rent = Double.parseDouble(st1.nextToken());
bw.write(str);
bw.write(System.lineSeparator());
}
tax = rent * intRate;
total = rent + tax;
payment = total / months;
} 
catch (Exception e) { System.err.println("Error: " + e.getMessage()); }


bw.write("Number of months of the loan:        " + months + "n");
bw.write("Your payment amount each month is:   " + total);
}
}

这是输入文件

Duster  425
Gomer   200
Wades   450
Stines  175

这些是我得到的错误

---jGRASP exec: javac -g project88.java
project88.java:35: error: variable rent might not have been initialized
tax = rent * intRate;
^
project88.java:44: error: variable total might not have been initialized
bw.write("Your payment amount each month is:   " + total);
^
project88.java:11: error: unreported exception FileNotFoundException; 
must be caught or declared to be thrown
BufferedReader br = new BufferedReader(new 
FileReader("d:/Data/Project3.txt"));
^
project88.java:12: error: unreported exception IOException; must be 
caught or declared to be thrown
BufferedWriter bw = new BufferedWriter(new 
FileWriter("d:/Data/Project3OutData.txt"));
^
project88.java:43: error: unreported exception IOException; must be 
caught or declared to be thrown
bw.write("Number of months of the loan:        " + months + "n");
^
project88.java:44: error: unreported exception IOException; must be 
caught or declared to be thrown
bw.write("Your payment amount each month is:   " + total);
^
6 errors

br.readLine((第一次可能返回null,因此"租金;可能未初始化。您需要处理这个问题以及没有输入的情况。

total需要初始化为零。

其余的是打开和写入需要使用try/catch处理的文件时的已检查异常。

此外,您还假设nextToken((不会引发(未检查的(异常NoSuchElementException,而您不应该这样做。

即使你";知道";输入文件就在那里,并且以您期望的形式,您的代码不应该(在某些情况下也不能(假设这一点。对于这样一个简单的程序,当出现任何问题时,您可能应该向stderr打印一条错误消息,并从main或(更好的(出口返回一个非零值。为了让这个代码防弹,它可能会变成现在的三倍大,但事情就是这样。

或者,如果你只是想";工作";,您可以修复未初始化的变量,并声明由"抛出的已检查异常;"main";,但这是不好的做法,可能是一个坏习惯的开始。

最新更新