Java 文件扫描程序无法正常挂起
试图制作一个程序,读取包含手机号码和每月费用的文件,并输出低于用户输入阈值的号码和费用。但是,在运行时,在用户输入阈值后,文件将永久挂起 代码如下所示:Java 文件扫描程序无法正常挂起,java,Java,试图制作一个程序,读取包含手机号码和每月费用的文件,并输出低于用户输入阈值的号码和费用。但是,在运行时,在用户输入阈值后,文件将永久挂起 代码如下所示: import java.io.*; import java.util.Scanner; import java.util.ArrayList; public class exam1 { public static void main (String[]args) throws IOException { Scanner G = n
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());
}
在此循环中:
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());
}
问题出在循环时
while (fileInput.hasNextLine())
{
b++;
}
fileInput.hasNextLine()
将始终返回true,因为您从未读取该行,并且将永远处于第一行。问题出在循环时
while (fileInput.hasNextLine())
{
b++;
}
fileInput.hasNextLine()
将始终返回true,因为您从未读过这一行,并且将永远处于第一行。您缺少的“明显的”东西是在红色循环中关闭文件。您缺少的“明显的”东西是在红色循环中关闭文件。谢谢!这就解决了问题。然而,我意识到我的输出是错误的。无论我在运行程序时为阈值设置了什么,它都只返回输入文件的第二行。@LeviFM在运行程序时出现了一些格式问题(您没有换行符,所以所有的打印语句都在一行上),但除此之外,它生成了正确的输出!这就解决了问题。然而,我意识到我的输出是错误的。无论我在运行程序时为阈值设置了什么,它都只返回输入文件的第二行。@LeviFM在运行程序时出现了一些格式问题(您没有换行符,所以所有的打印语句都在一行上),但除此之外,它生成了正确的输出