为了测试,我在一个文本文件中得到了三个名字。
Joe ,Smith
Jim ,Jones
Bob ,Johnson
我通过在 while
循环的末尾添加第二个 s=reader.readLine();
来修复永恒循环,但是当我运行下面的代码时,我得到以下输出:
JoeSmith
JoeSmith
JimJones
JimJones
BobJohnson
BobJohnson
如何防止重名?我的第二个 s=reader.readLine();
放错了吗? * 废话。没关系。我正在打印源数据和从中创建的数组字段。哎呀。
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
。
您的代码需要更多地遵循:
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()
建议。
问题改变后的后续编辑:
I fixed the eternal looping by adding a second s=reader.readLine(); at the end of my while loop, but when I run the code below, I get the following output:
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 行输出。
关于java - 为什么我在用 Java 读取文本文件时会循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10343706/