![](/img/trans.png)
[英]Why am I getting an ArrayIndexOutOfBoundsException when I try to tokenize the input from the console (Java)?
[英]Why am I getting an exception when redirecting input from file, but not manual input for a Java program?
這是我的輸入文件(稱為input.txt)的內容
C:\DIRECTORY_REMOVED>type input.txt
180
3
640 480
120 300
180 180
這是我要針對它運行的Java程序(一個朋友寫的),
import java.io.*;
import java.util.*;
class Square
{
public static void main (String args[]) throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String s;
s = stdin.readLine();
int L = Integer.parseInt(s);
String m;
m = stdin.readLine();
int N = Integer.parseInt(m);
int a = 1;
while (a <= N)
{
Scanner sc = new Scanner(System.in);
int W = sc.nextInt();
int H = sc.nextInt();
if ( W < L || H < L)
{
System.out.println("UPLOAD ANOTHER");
}
else if ( W >= L && H >= L && W == H)
{
System.out.println("ACCEPTED");
}
else
{
System.out.println("CROP IT");
}
a++;
}
}
}
編譯后,如果我要在命令行上手動輸入輸入,則程序運行時不會出現問題(請參見下文),
C:\DIRECTORY_REMOVED>java Square
180
3
640 480
CROP IT
120 300
UPLOAD ANOTHER
180 180
ACCEPTED
但是,如果我嘗試從較早的文本文件重定向輸入,則會引發異常,
C:\DIRECTORY_REMOVED>java Square < input.txt
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Square.main(Square.java:18)
如果將源代碼重寫為在初始輸入行中使用Scanner而不是BufferedReader,則該異常消失。 我不明白為什么?
如果有人從命令提示符手動輸入數據,但是從文件重定向失敗,為什么有人能很好地解釋為什么代碼運行得很好呢?
在Windows 7(64位)和Windows 8.1(64位)上已經觀察到相同的行為。 使用的JDK也是64位(Java版本8)。
主題外:該程序是為回答HackerEarth上的一個實踐難題而編寫的-http: //www.hackerearth.com/problem/algorithm/roy-and-profile-picture/
標准控制台流是行緩沖的 。 這意味着讀取一行數據的系統調用將在讀取一行后返回,即使有更多輸入可用。 這意味着環繞System.in
的BufferedReader
一次只能讀取一行以填充內部緩沖區。
然后,將Scanner
包裹在System.in
周圍時,它可以從BufferedReader
停止的地方繼續。
文件流是塊緩沖的 。 如果文件足夠大,系統調用將填充整個提供的緩沖區。 由於您的文件很小,因此這意味着BufferedReader
將一次性讀取整個文件,然后從其內部緩沖區提供數據,而基礎流位於EOF。
這意味着,當您將Scanner
包裹在System.in
周圍時,它所看到的只是EOF處的流,它無法讀取任何內容。
將Scanner
包裹在您的stdin
變量周圍,或者從頭開始使用它而不是BufferedReader
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.