java - 如何让我的程序读取 Java 中的 txt 文件?

标签 java

该程序的一般功能是从txt文件中提取所有信息,将其输入到数组中,然后将用户输入的ID与输入到数组中的ID进行比较,并返回true或false。我编写了该程序,但出现了 InputMismatchException。当我将该函数放入 try/catch 语句中时,运行它时它会返回 null。

这是我的 validator 类:

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

public class Validator
{
    private int[] valid = new int[18];

    public Validator(String filename) throws IOException
    {
        try
        {
            File file = new File(filename);
            Scanner inputFile = new Scanner(file);
            int index = 0;

            while (inputFile.hasNext())
            {
                valid[index] = inputFile.nextInt();

                index++;
            }

            inputFile.close();
        }

        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }


    public boolean isValid(int number)
    {
        int index = 0;
        boolean found = false;

        while (!found && index < valid.length)
        {
          if (valid[index] == number)
          {
              found = true;
          }

          index++;
        }

        return found;
    }
}

主要方法:

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

public class ChargeAccountModification
{
    public static void main(String[] args) throws IOException
    {
        int number;

        Scanner keyboard = new Scanner(System.in);

        System.out.println("Brandon Woodruff    12/3/16");

        System.out.print("Enter your charge account number: ");
        number = keyboard.nextInt();

        Validator validator = new Validator("AccountNumbers.txt");

        if (validator.isValid(number) == true)
        {
            System.out.println("That's a valid account number.");
        }

        else
        {
            System.out.println("That's an INVALID account number.");
        }
    }
}

最后是txt信息。顺便说一句,该 txt 文件名为 AccountNumbers.txt。

5658845 4520125 7895122 8777541 8451277 1302850 8080152 4562555 5552012 5050552 7825877 1250255 1005231 6545231 3852085 7576651 7881200 4581002

它们实际上各自出现在列表中自己的行上,但我似乎无法让它像那样显示。

最佳答案

在此代码中:

    while (inputFile.hasNext()) {
        valid[index] = inputFile.nextInt();

        index++;
    }

尝试用 hasNextInt() 替换 hasNext() :

    while (inputFile.hasNextInt()){
        valid[index] = inputFile.nextInt();

        index++;
    }

否则它会读取空格,而空格不是数字。

如果不起作用,您还可以使用带有空格的分隔符:

Scanner s = new Scanner(file).useDelimiter("\\s");

关于java - 如何让我的程序读取 Java 中的 txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41066706/

相关文章:

java - 如何提取两个 "/"字符之间的字符串

java - 用户在数组中输入 10 个数字,我该如何编写代码来查找该数字并输出它在数组中的位置?

java - 在 JFrame 中绘制矩形不起作用

java - 如何在ant build xml中设置java_home

java - 我的编码显示这些错误,如何解决?

JavaFX-CSS:如何将父级的 "move"样式传递给子级?

java - 我可以从内部类访问注入(inject)的 ejb 吗?

java - java中的超时方法

java - 将 JPanel 添加到 JSplitPane 中的 JScrollPane

java - 如果 ID 在数据库中可用,则更新,否则插入