【发布时间】:2016-01-04 20:27:55
【问题描述】:
我想检查具有以下内容的文本文件的输入:
task1 2 3 task2 2 3 task3 2 3 task4 4 5 task5 4 5
task6 7 9 task7 7 9 task8 7 9 task9 7 9
task10 7 9 task11 7 9 task12 7 9 task13 7 9
task14 7 9 task15 7 9 task16 10 11 task17 10 11
task18 10 11 task19 10 11 task20 10 12
我尝试了以下代码,但它不起作用,不知道哪里出了问题以及如何继续使用扫描仪的 hasNext() 和 hasNextInt() 来检查内容,使其以非整数开头,例如 task1字母数字字符,后跟 2 个整数,然后在整个文件中重复这种格式,如上所示。
Scanner s;
try {
s = new Scanner(readFile); // create new Scanner scanning file and references variable s to it
while (s.hasNext()) { // when there is the next string separated by default whitespace
// check whether contents of file follow the right format
if (!s.hasNextInt()) { // if s.next() is not an integer
while (s.hasNext()) {
if (s.hasNextInt()) { // if s.next() that follows is an integer
while (s.hasNext()) {
if (s.hasNextInt()) { // if s.next() that follows is an integer
System.out.println("The content of the file follows the right format.");
break;
}
}
}
}
} else { // if s.next() does not follow right format
System.out.println("The content of the file does not follow the right format.");
break;
}
}
s.close();
}
【问题讨论】:
标签: integer pattern-matching java.util.scanner token file-read