Java nextLine()跳过while循环结束时的行。丢失数据
我试图只在每次循环结束时运行nextLine(),这样每次迭代它都会以新行开始循环,但在最后一次运行结束时,我不希望它运行nextLine(),因为它会跳过我程序其余部分所需的数据。我该如何解决这个问题Java nextLine()跳过while循环结束时的行。丢失数据,java,while-loop,text-files,java.util.scanner,Java,While Loop,Text Files,Java.util.scanner,我试图只在每次循环结束时运行nextLine(),这样每次迭代它都会以新行开始循环,但在最后一次运行结束时,我不希望它运行nextLine(),因为它会跳过我程序其余部分所需的数据。我该如何解决这个问题 String hasInt = fileIn.nextLine(); while(Character.isDigit(hasInt.charAt(0))) { data = hasInt.split(","
String hasInt = fileIn.nextLine();
while(Character.isDigit(hasInt.charAt(0)))
{
data = hasInt.split(",");
info = Integer.parseInt(data[0]);
def = data[1];
case = data[2];
free = data[3];
Case newCase = new Case(info, def, case, free);
miner.addCase(newCase);
hasInt = fileIn.nextLine();
}
将所有这些结合到for循环中似乎是可行的,这让我一路通过了这个循环,而且似乎是可行的,但是现在在这个方法的开始,它陷入了一个无限循环中
while(fileIn.hasNextLine())
{
if(fileIn.hasNext("[A-Za-z]+"))
{
我不知道它会有多干净,但是;似乎可以在while循环之后使用hasInt来获取不希望跳过的值。可以尝试将语句合并到for循环中:
do {
String hasInt = fileIn.nextLine();
if (!Character.isDigit(hasInt.charAt(0)) {
break;
}
// rest of your code here
} while(true);
for(
String hasInt = fileIn.nextLine();
Character.isDigit(hasInt.charAt(0));
hasInt = fileIn.nextLine()
) {
data = hasInt.split(",");
info = Integer.parseInt(data[0]);
def = data[1];
case = data[2];
free = data[3];
Case newCase = new Case(info, def, case, free);
miner.addCase(newCase);
}
您好,您不会丢失数据,因为您上次读取的数据位于hasInt变量中。所以在while循环之后使用它
String hasInt = fileIn.nextLine();
while(Character.isDigit(hasInt.charAt(0)))
{
data = hasInt.split(",");
info = Integer.parseInt(data[0]);
def = data[1];
case = data[2];
free = data[3];
Case newCase = new Case(info, def, case, free);
miner.addCase(newCase);
hasInt = fileIn.nextLine();
}
//use the hasInt variable here to get the last read data...
不能将
case
用作变量名,此代码不会编译;请编辑并粘贴真正的编解码器现在卡在方法顶部的无限循环中,我发布了代码它卡在哪里?如果你有新问题,我建议将其作为一个单独的问题发布,其中包含所有相关的代码。