繁体   English   中英

为什么我在Java中读取文本文件时循环?

[英]Why am I looping while reading a text file in Java?

为了测试,我在文本文件中有三个名字。

Joe       ,Smith
Jim       ,Jones
Bob       ,Johnson

我通过添加第二个s=reader.readLine();修复永恒循环s=reader.readLine(); 在我的while循环结束while ,但是当我运行下面的代码时,我得到以下输出:

JoeSmith
JoeSmith
JimJones
JimJones
BobJohnson
BobJohnson

如何防止重复的名称? 是我的第二个s=reader.readLine(); 放错了? *废话。 没关系。 我正在打印源数据和从中创建的数组字段。 Oy公司。

import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.text.*;
import javax.swing.JOptionPane;
//
public class VPass
{
    public static void main(String[] args)
    {
        final String FIRST_FORMAT = "          ";
        final String LAST_FORMAT = "          ";
        String delimiter = ",";
        String s = FIRST_FORMAT + delimiter + LAST_FORMAT ;
        String[] array = new String[2];
        Scanner kb = new Scanner(System.in);
        Path file = Paths.get("NameLIst.txt");
        try
        {    
            InputStream iStream=new BufferedInputStream(Files.newInputStream(file));
            BufferedReader reader=new BufferedReader(new InputStreamReader(iStream));
            s=reader.readLine();
            while(s != null)
            {
                array = s.split(delimiter);
                String firstName = array[0];
                String lastName = array[1];
                System.out.println(array[0]+array[1]+"\n"+firstName+lastName);
                s=reader.readLine();
            }
    }
    catch(Exception e)
    {
        System.out.println("Message: " + e);
    }
   }
  }

s=reader.readLine(); 再次在你的while循环结束时。 最终它将变为null并且您的循环将退出。

在第一次循环迭代后,您永远不会更新s

您的代码需要更多:

while ((s = reader.readLine()) != null)
{
  array = s.split(delimiter);
  String firstName = array[0].trim();
  String lastName = array[1].trim();
  System.out.println(array[0]+array[1]+"\n"+userName+password);
}

编辑:根据Sanchit的评论添加了trim()建议。


问题发生变化后的后续编辑:

我通过添加第二个s = reader.readLine()来修复永恒循环; 在我的while循环结束时,但是当我运行下面的代码时,我得到以下输出:

为JoeSmith

为JoeSmith

JimJones

JimJones

BobJohnson

BobJohnson

如果我们查看您的代码:

while(s != null)
{
  array = s.split(delimiter);
  String firstName = array[0];
  String lastName = array[1];
  System.out.println(array[0]+array[1]+"\n"+firstName+lastName);   // <-- this prints 2 lines of output
  s=reader.readLine();
}

...你看到你为每个循环迭代输出2行输出。

暂无
暂无

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

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