[英]How to detect EOF in Java?
我已經嘗試了一些方法來檢測我的代碼中的 EOF,但它仍然無法正常工作。 我試過使用 BufferedReader、Scanner 和使用 char u001a 來標記 EOF,但對我的代碼仍然沒有任何意義。 這是我最后的代碼:
Scanner n=new Scanner(System.in);
String input;
int counter=0;
while(n.hasNextLine())
{
input=n.nextLine();
char[] charInput=input.toCharArray();
for (int i = 0; i < input.length(); i++) {
if(charInput[i]=='"')
{
if(counter%2==0)
{
System.out.print("``");
}
else
{
System.out.print("''");
}
counter++;
}
else
{
System.out.print(charInput[i]);
}
}
System.out.print("\n");
}
該程序應該在已經到達 EOF 時停止,但我不知道為什么,由於某些原因它繼續運行並導致運行時錯誤。 請幫忙。 順便說一句,我是新來的,如果我的問題不是很清楚,我很抱歉,先謝謝你:)
它一直在運行,因為它沒有遇到 EOF。 在流結束時:
read()
返回 -1。read(byte[])
返回-1。read(byte[], int, int)
返回 -1。readLine()
返回 null。readXXX()
拋出EOFException
。Scanner.hasNextXXX()
對任何 X 返回 false。Scanner.nextXXX()
為任何 X 拋出NoSuchElementException
。 除非您遇到過其中之一,否則您的程序還沒有遇到流結束。 注意\
是一個 Ctrl/z。 不是EOF。 EOF 不是字符值。
這就是我所做的
Scanner s = new Scanner(f); //f is the file object
while(s.hasNext())
{
String ss = s.nextLine();
System.out.println(ss);
}
為我工作
特別是對於System.in
,您應該能夠通過FileDescriptor.in.valid()
檢查支持FileDescriptor
是否仍然打開。
簡單演示:
$ cat FD.java
public class FD {
public static void main(String[] args) throws Exception {
System.out.println(java.io.FileDescriptor.in.valid());
System.in.close();
System.out.println(java.io.FileDescriptor.in.valid());
}
}
$ javac FD.java
$ java -cp . FD
true
false
您可以使用try 和 catch 。
Scanner n=new Scanner(System.in);
String input;
int counter=0;
input=n.nextLine();
try{
while(input!=null)
{
char[] charInput=input.toCharArray();
for (int i = 0; i < input.length(); i++) {
if(charInput[i]=='"')
{
if(counter%2==0)
{
System.out.print("``");
}
else
{
System.out.print("''");
}
counter++;
}
else
{
System.out.print(charInput[i]);
}
}
System.out.print("\n");
input=n.nextLine();
}
}catch(Exception e){
}
在這里,當你給Ctrl+z 時, Scanner.nextLine()
會給你NoSuchElementException
。 將此異常用作 EOF 的條件。 要處理此異常,請使用 try 和 catch。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.