gpt4 book ai didi

java - 文件扫描程序无限期挂起

转载 作者:行者123 更新时间:2023-12-01 19:45:24 26 4
gpt4 key购买 nike

尝试编写一个程序,读取包含每月手机号码和费用的文件,并输出低于用户输入阈值的号码和费用。但是,运行时,文件在用户输入阈值后无限期挂起。

代码如下所示:

import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;

public class exam1
{
public static void main (String[]args) throws IOException
{


Scanner G = new Scanner (System.in);
ArrayList<String> cellNum = new ArrayList<String>();
ArrayList<Float> cost = new ArrayList<Float>();
String filename = "";
int i=0, b=0;
float thresh = 0;

System.out.print("Enter filename: ");
filename = G.next();
File file = new File (filename);
Scanner fileInput = new Scanner (file);
System.out.print("\nEnter Cell Bill Threshold: ");
thresh = G.nextFloat();

while (fileInput.hasNextLine())
{
b++;
}
fileInput.close();

while (fileInput.hasNextLine())
{
for (i=0; i < b; i++)
{
cellNum.add(fileInput.next());
cost.add(fileInput.nextFloat());
}
fileInput.close();
}

for (i=0; i<cost.size();i++)
{
if (cost.get(i) > thresh )
{
cellNum.remove(i);
cost.remove(i);

}
}

System.out.print("\nBills exceeding threshold: ");
System.out.printf("\n%12s%8s", "Number", "Amount");

for (i=0; i<cost.size(); i++)
{
System.out.printf("%12s%8.2f", cellNum.get(i), cost.get(i));
}
}
}

正在读取的相关文件如下所示:

403-222-1023 37.24
403-983-1942 46.44
403-982-1952 50.35

我觉得我错过了一些非常明显的东西,但这里将不胜感激。感谢您抽出宝贵的时间,很抱歉打扰您。

最佳答案

在此循环中:

while (fileInput.hasNextLine())
{
b++;
}

您永远不会使用 fileInput 中的下一行,因此 hasNextLine() 将始终返回 true,从而导致无限循环。您需要在 while 循环内调用 nextLine(),以便 hasNextLine() 在某个时刻返回 false。

<小时/>

然后你也这样做:

fileInput.close();

while (fileInput.hasNextLine()) {
//...
fileInput.close();
}

您无法关闭源然后尝试从中读取。仅在完全完成读取后才关闭扫描仪

如果您确定每行都采用指定的格式,您可以执行以下操作:

while (fileInput.hasNextLine())
{
cellNum.add(fileInput.next());
cost.add(fileInput.nextFloat());
}

关于java - 文件扫描程序无限期挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53561526/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com