【发布时间】:2017-01-30 04:17:53
【问题描述】:
我正在编写一个可以使用经典加密方法对消息进行编码和解码的程序。消息将从文件中读取并写入输出文件。以下程序是用 java 编写的,并且编译没有错误。当我运行程序以测试它是否在我给它输入和输出文件的名称之后到目前为止它运行到某种异常抛出错误。我认为问题在于代码中的 for 循环。这是一个将所有消息存储到字符数组中的循环。有什么建议可以修复它或其他更好的数据结构(如堆栈或队列)?
import java.io.*;
import java.util.*;
class CryptoProject1
{
static char eord;
static Scanner cin=new Scanner(System.in);
static char [] message=new char[10000];
public static void main (String [] args)
throws IOException
{
//getting the input txt file name from user
String infilename;
System.out.println("Please give the name of the input file.");
infilename=cin.nextLine();
Scanner fileread=new Scanner (new FileReader(infilename));
//getting the output txt file name from user
String outfilename;
System.out.println("Please give the name of the output file.");
outfilename=cin.nextLine();
PrintWriter filewrite=new PrintWriter(new FileWriter(outfilename));
//saving the message into an array
//construct/make it into a usable function??
for(int i=0; i<message.length; i++)
{
message[i]=fileread.next().charAt(0);
}
//trial to make sure it reads and writes correctly
//printing the message onto the output file
for(int i=0; i<message.length; i++)
{
filewrite.print(message[i]);
}
}
【问题讨论】:
-
“它遇到了某种异常”。有什么例外?它应该准确地告诉您出了什么问题,以及哪里出了问题。
-
在你的第一个循环中添加一个检查:if(fileread.hasNext()) 然后执行操作 else break
-
@resueman 这是它给出的错误消息:java.util.Scanner.throwFor(Scanner.java:907) 处的线程“main”java.util.NoSuchElementException 中的异常。 Scanner.next(Scanner.java:1416) 在 CryptoProject1.main(CryptoProject1.java:112)
标签: java cryptography filereader filewriter