gpt4 book ai didi

java - 创建一个程序来读取文本文件并计算 5 的数量。输出关闭五分之一

转载 作者:行者123 更新时间:2023-12-02 02:30:22 24 4
gpt4 key购买 nike

当我运行该程序时,一切似乎都工作正常,只是它计数为 8 个五,而实际上 txt 文件中有 9 个五。

import java.io.*;
import java.util.*;
public class FileIO2
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);

String filename = "Input1.txt";

Scanner myFile = null;
try
{
myFile = new Scanner(new FileInputStream(filename));
}
catch(Exception e)
{
System.out.println("File not found.");
System.exit(0); //close the program
}


int countNums = 0;
while(myFile.hasNext())
{
if(myFile.hasNextInt(5))
{
countNums++;
}
myFile.next();
}
System.out.println("There were " + countNums + " fives in " + filename);
}
}

Input1.txt 文件内容:

5 9 3 2 0 5 3 0 8 5 5 55 94 3 0 65 5 5

最佳答案

我建议您对代码进行一些重构。

这个解决方案工作正常:

public class FileIO2 {
private static final String PATH_TO_FILE = "/home/user/temp/Input1.txt";
private static final int NUMBER_TO_FIND = 5;

public static void main(String[] args) throws FileNotFoundException {
int counter = 0;

try (Scanner scanner = new Scanner(new File(PATH_TO_FILE))) {
while (scanner.hasNextInt()) {
int currentInt = scanner.nextInt();
if (currentInt == NUMBER_TO_FIND) {
counter++;
}
}
}

System.out.println("There were " + counter + " fives in " + PATH_TO_FILE);
}
}

代码中有问题的行是 myFile.hasNextInt(5)

关于java - 创建一个程序来读取文本文件并计算 5 的数量。输出关闭五分之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47211354/

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