文字列の配列リストにスペースを含むテキスト ファイルを入力しようとしています。これにより、配列リストの各文字列に最初と 2 番目の数字の間にスペースが含まれ、先頭または末尾にスペースが含まれなくなります。残念ながら、実行中に次のエラーシーケンスが発生します。
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at scannerTest.main(scannerTest.java:26)
以下は私のコードです:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class scannerTest
{
private static ArrayList<String> myStore = new ArrayList<String>();
public static void main(String[] args)
{
int id = 0;
int inv = 0;
boolean idStarted = false;
boolean idFinished = false;
try
{
Scanner file = new Scanner(new File("file50.txt"));
System.out.println("File: " + "file50.txt");
while (file.hasNextLine())
{
for (int b = 0; b < (file.nextLine()).length(); b++)
{
if (!file.next().equals(" "))
{
id = id + Integer.parseInt(file.next());
idStarted = true;
}
if (idStarted = true && file.next().equals(" "))
{
idFinished = true;
}
if (idFinished = true && !file.next().equals(" "))
inv = inv + Integer.parseInt(file.next());
}
String result = Integer.toString(id) + " " + Integer.toString(inv);
myStore.add(result);
}
}
catch (FileNotFoundException e)
{
System.out.println("ERROR: File '" + "file50.txt" + "' not found!");
}
System.out.println(myStore);
}
}
ファイルは次のようになります。
3679 87
196 60
17914 12
18618 64
2370 65
584 85
18524 34
12024 5
6992 76
18410 56
9267 68
18995 56
6265 58
6835 94
14151 82
11485 39
15559 33
18465 27
19967 45
13520 38
5529 11
3433 5
17911 96
18181 60
11549 88
14896 81
184 14
4329 64
18871 69
15141 87
11584 32
14088 92
18061 3
206 31
13066 8
19623 88
12705 14
9351 8
17753 70
15917 51
768 85
15814 60
15320 82
8303 90
7282 73
14092 48
10629 19
12917 63
15006 53
12328 63
26 行目でエラーが発生している理由がわかりません。
if (!file.next().equals(" "))
私が行おうとしているのは、行の次のオブジェクトが空白であるかどうかを確認し、その場合は無視することです。この問題に関する助けをいただければ幸いです。