我正在編寫一個程序,可以使用傳統的加密方法對消息進行編碼和解碼。該消息將從文件讀入並寫入輸出文件。下面的程序是用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]);
}
}
「它運行到某種的例外「。什麼是例外?它應該告訴你到底發生了什麼問題,以及在哪裏。 – resueman
在你的第一個循環中添加一個檢查:if(fileread.hasNext()),然後執行動作else break – Angen
@resueman這是它給出的錯誤信息:線程「main」中的異常java.util.NoSuchElementException at java .util.Scanner.throwFor(Scanner.java:907) at java.util.Scanner.next(Scanner.java:1416) at CryptoProject1.main(CryptoProject1.java:112) –