【发布时间】:2015-04-18 02:00:08
【问题描述】:
我正在编写一个程序,它使用 Scanner 从文件中读取行。当有空行时,我想处理已经看到并存储在字符串数组列表中的行。然后我希望它跳到文件中的下一行,直到它再次看到一个空行。然后处理这些行,直到文件被完全读取。
我似乎无法解决这个问题?到目前为止,我的程序一直适用于这组行,直到它到达空行但随后没有进展。
while scan.hasnextLine() 循环完成后,可以在我的代码中看到我想做的处理。
感谢您的帮助。
public static void main(String[]argv){
Scanner scan = new Scanner(System.in);
//read in the line from stdin, if it's empty, then break out OR process it
while (scan.hasNextLine()){
String tempLine = scan.nextLine();
if (tempLine.equals("")){
break;
}
columnCount = tempLine.length();
tempArray.add(tempLine); //add temp line to string array initial
rowCount++;
}
System.out.println("rowcount: "+rowCount);
System.out.println("columnCount: "+columnCount);
//set the 2D array to the right size
epidemicArray = new char[rowCount][columnCount];
//populate 2d array with strings from tempArray
updateArray();
System.out.println("original array:");
printArray();
//copy populated 2d array to another array
copyArray(epidemicArrayCopy);
//iterate over array to get final state
do{
getFinalState(epidemicArray);
} while (countChanges > 0);
printArray();
}
【问题讨论】:
-
根据您的代码,您的循环在找到第一个空行时会中断。所以它不会读取其余的行。最好再努力一点;)
-
尝试把处理一批行的逻辑封装在一个函数中,一遍遍地调用函数……
-
@Alejandro 我试过了,但是如果我在该批次的行函数中将 rowCount 设置为 0,它会在返回时调用 rowCount ++。而且我不能在处理行之前放置 rowCount++,因为如果它是空白行我不想添加到 rowCount
标签: java arrays iteration java.util.scanner