因此,首先,這是家庭作業,儘管不是我的。這是我的姐夫的。自從我做電腦以來,他問我尋求幫助,但我只用C++工作。他正在使用System.in
將文本輸入到文件中,直到他獲得EOF
。之後,他創建了一個實例Scanner
並調用實例上的nextLine
以嘗試獲取filename
並獲得NoSuchElementException
。根據Javadoc的說法,這意味着沒有任何輸入信息會被接收到,在使用System.in
並在鍵盤上打字時看起來像是一件奇怪的事情。我的懷疑是EOF
字符不知道怎麼消耗。他的代碼在今晚的午夜時間到期,他還完成了一切(我建議他使用虛擬文件名並回到問題)。獲取NoSuchElementException使用Scanner類讀取Standard.In讀取EOF後
這裏是他的代碼:
import java.util.*;
import java.io.*;
public class FileTest
{
public static void main(String[] args)
{
createFile();
readFile();
}
public static void createFile()
{
//Variables
InputStream istream;
PrintStream ostream;
istream = System.in;
ostream = System.out;
Scanner keyboard = new Scanner(System.in);
int lastEntry = 0;
final int EOF = -1;
//Asks user for filename.
try
{
String fileName;
System.out.println("Please enter the filename of the file you want to open: ");
fileName = keyboard.next();
//Creates specified file.
File currentFile = new File(fileName);
//Checks if file already exists.
while(currentFile.exists())
{
System.out.println(fileName + " already exists");
System.out.println("Error: To prevent tis file from being overwritten please enter another file name");
fileName = keyboard.nextLine();
}
//Asks user for information they want stored in file.
try
{
ostream = new PrintStream(fileName);
System.out.println("Please enter what you would like to put in the file and press Ctrl+Z when finished: ");
//Writes information to file.
try
{
while((lastEntry = istream.read()) != EOF)
ostream.write(lastEntry);
}
catch(Exception e)
{
System.out.println("Error: " +e.getMessage());
}
}
catch(Exception f)
{
System.out.println("Error: " +e.getMessage());
}
}
finally
{
}
}
public static void readFile()
{
InputStream input;
PrintStream output;
output = System.out;
int lastEntry = 0;
final int EOF = -1;
Scanner keyboard2 = new Scanner(System.in);
//Asks user for filename.
String newFile;
System.out.println("Please enter the filename of the file you want to open: ");
newFile = keyboard2.next();
}
}
他越來越對newFile = keyboard2.next()
行NoSuchElementException
錯誤。我瀏覽了大量的例子,發現有人發佈這個問題,但我還沒有找到解決方案,所以我想我會把我的(可疑的)聲譽放在他的位置上。任何人都知道他如何才能使這個工作?
你有沒有試過kerboard2.nextLine(); ??? – buch11
也有同樣的錯誤。 –
上面的代碼進入無限循環哥們,ctrl + z不會讓你走出第一個函數,我想首先你需要糾正那個...... – buch11