繁体   English   中英

FileReader 只读取 TXT 的前两行

[英]FileReader only reads the first two lines of TXT

我尝试编写一个 java 程序来读取用户输入的文本并检查输入的文本是否重复。 但是我遇到了一个问题,FileReader只读取了特定TXT的前两行。 我已经向其他人寻求帮助,但他们无法弄清楚出了什么问题? 谁能帮我? 谢谢!

PS 如果我输入 theodora,它会返回正确的 output。但是如果我输入 sophia,txt 文件中的另一个名字,它会返回“联系人不存在”

在此处输入图像描述

    Scanner fr1 = new Scanner (listFile);
    System.out.print ("Enter a contact name: ");

    inName = keyboard.nextLine ();
    
    if (!fr1.hasNext()){
        System.out.print ("Contact doesn't exist");
    }else{
        while (true){
            String strName = fr1.next();
            String strPhone = fr1.next();
            if (strName.equals(inName.trim())){
                System.out.print ("Contact name: " + strName+", Phone number: " + strPhone);
                keyboard.nextLine ();
                break;
            }else{
                System.out.print ("Contact doesn't exist");
                break;
            }
        }
    }fr1.close();

您好 您可以使用 List 来存储 txt 中的所有数据,然后从中获取数据

{
    File file = new File(
            "\\Desktop\\test.txt");

    BufferedReader br
            = new BufferedReader(new FileReader(file));

    String st;

    List contactList = new ArrayList();
    while ((st = br.readLine()) != null)
        contactList.add(st);

    if(contactList.contains("Mona")){
        int index = contactList.indexOf("Mona");
        System.out.print ("Contact name: " + contactList.get(index)+", Phone number: " + contactList.get(index+1));
    }
}

我的 txt 包含: Tupan 123456 Mona 87546 Zen 97679

我得到的output是联系人姓名:Mona,电话号码:87546

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM