将文本文件中的数据与Java中的用户输入相匹配

时间:2010-09-17 03:51:54

标签: java login text-files

我需要从记事本文件(下方)中检索PIN,并使用用户键入的PIN进行检查。我已经尝试了好几天,但到目前为止,我提出的解决方案只有在我输入完整行(即1598 01-10-102203-0 95000)时才能给出正确的输出。此外,它还会为每条记录显示“无效的PIN”。

PIN AccountNo   Balance
1598    01-10-102203-0  95000
4895    01-10-102248-0  45000
9512    01-10-102215-0  125000
6125    01-10-102248    85000

Output - You have login!

    Invalid PIN    
    Invalid PIN
    Invalid PIN
BufferedReader getIt = new BufferedReader(new InputStreamReader(System.in));
String userPIN = "";

try {
    // Open the file that is the first command line parameter
    FileInputStream fstream = new FileInputStream(
        "D:\\Studies\\BCAS\\HND\\Semester 1\\Programming "
        + "Concepts\\Assignment\\AccountInfo.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    System.out.println("Enter PIN");
    userPIN = getIt.readLine();

    while ((strLine = br.readLine()) != null) {
        // Print the content on the console#    
        if (userPIN.equals(strLine)) {
            System.out.println("You have login!");
        } else {
            System.out.println("Invalid PIN!");
        }
    }
    //Close the input stream
    in.close();
} catch (Exception e) {//Catch exception if any
    System.err.println("Error: " + e.getMessage());
}

1 个答案:

答案 0 :(得分:3)

Jon Freedman's优秀answer的一个基本要素,您应该考虑接受,是您必须将传入的文本行拆分为其组成部分,以便将它们与键入的内容进行比较。这是一种方法:

String line = "1598 01-10-102203-0 95000";
for (String s : line.split(" ")) {
    System.out.println(s);
}

这会产生以下输出:

1598
01-10-102203-0
95000

附录:

while ((strLine = br.readLine()) != null) {
    String[] a = strLine.split(" ");
    // now the array a contains the three parts
    ...
}