-1

背景:代码应该通过一个 csv 文件(第二个链接),找到用户名和密码,然后确认并显示所有信息或写入错误。但现在它只说错误。提前喝彩。

http://pastebin.com/YBpKRKe2 http://pastebin.com/9K3nwYG3

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

public class CSVRead
{
    public static void main(String[] args)
    throws Exception
    {

        BufferedReader CSVFile =
            new BufferedReader(new FileReader("test123.csv"));
        int invalidvar = 1;

        Scanner input = new Scanner(System.in);
        System.out.println("Enter your email");
        String email =input.nextLine();

        System.out.println("Enter your password");
        String password =input.nextLine();

        String dataRow = CSVFile.readLine(); // Read first line.
        // The while checks to see if the data is null. If
        // it is, we've hit the end of the file. If not,
        // process the data.

        while (dataRow != null)
        {
            String[] dataArray = dataRow.split("\\t");


            if ((dataArray[0].equals(email))
            &&(dataArray[1].equals(password)))
            {
                System.out.println("You email is " +dataArray[0]+".");
                System.out.println("You password is " +dataArray[1]+".");
                System.out.println("You first name is " +dataArray[2]+".");
                System.out.println("You second name is " +dataArray[3]+".");
                System.out.println("You street name is " +dataArray[4]+".");
                System.out.println("You city name is " +dataArray[5]+".");
                System.out.println("You postcode is " +dataArray[6]+".");
            }

            else
            {
            System.out.println("Error");
            break;
            }


            dataRow = CSVFile.readLine();
        }
        // Close the file once all data has been read.
        CSVFile.close();

        // End the printout with a blank line.
        System.out.println();

    } //main()
} // CSVRead
4

1 回答 1

0

您只检查 CSV 标头之后的第一条记录。您需要继续检查记录,直到EOF达到:

boolean found = false;
while (!found && dataRow != null) {
    String[] dataArray = dataRow.split("\\t");

    if ((dataArray[0].equals(email)) && (dataArray[1].equals(password))) {
        System.out.println("You email is " + dataArray[0] + ".");
            ...
        found = true;
    } 

    dataRow = csvFile.readLine();
}

System.out.println("Result of CSV search: " + found);

一些旁注:

  • IO 流应该在一个finally块中关闭。
  • Java 命名约定指示变量应以小写字母开头。
于 2013-02-01T22:45:17.160 回答