【发布时间】:2014-10-18 07:11:54
【问题描述】:
我有这个应用程序,它提示用户输入一个文本文件,从这个文本文件中,它包含整数和文本字符串。从那里,它应该写入另一个文本文件,result.txt。现在,由于我还是 IO 的新手,尽管文件已成功创建,但我在写入文件时遇到了问题。应用程序在用户输入文本文件名称后立即停止。那么你们能给我一些帮助吗?提前致谢!
import java.util.*;
import java.io.*;
class FileReadingExercise3 {
public static void main(String [] args)
{
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do
{
try
{
System.out.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if(a.equals("QUIT"))
{
System.exit(0);
}
fileInput = new Scanner(new File(a));
}
catch(FileNotFoundException e)
{
System.out.println("Error " + a + " does not exist.");
}
}while(fileInput == null);
PrintWriter output = null;
try
{
output = new PrintWriter(new File("result.txt"));
}
catch(IOException g)
{
System.out.println("Error");
System.exit(0);
}
while(fileInput.hasNext())
{
if(fileInput.hasNextInt())
{
int num = fileInput.nextInt();
sum += num;
String str = Integer.toString(num);
output.println(str);
}
}
fileInput.close();
output.close();
}
}
【问题讨论】:
-
a) 你为什么要两次
new File("result.txt"));? b) 你的while(fileInput.hasNext())后面跟着if(fileInput.hasNextInt())看起来很狡猾。如果 while 为真但 if 为假,则无限循环? -
@ScaryWombat 哦,对不起,那是试错,刚才忘了删除它。 erm 不知何故,我对我的 while 循环有点困惑,就像你提到的那样,哈哈。
-
但是你的错误到底是什么?
-
@ScaryWombat erm 整个东西编译没有错误,但是运行时,在我输入要读取的 txt 文件后它就卡住了。
标签: java exception io printwriter