读取文件以将数据存储在数组中时出错

时间:2015-11-26 16:49:58

标签: java arrays file stringtokenizer

我写的程序是用Java编写的。我试图让我的程序读取文件“name.txt”并将文本文件的值存储在一个数组中。

到目前为止,我正在使用一个将在我的主程序中读取的文本文件,一个名为People.java的服务类,它将用作我的程序的模板,我的主程序名为Names.java,它将读取文本文件并将其值存储到数组中。

name.txt:

John!Doe
Jane!Doe
Mike!Smith
John!Smith
George!Smith

People.java:

public class People
{
    String firstname = " ";
    String lastname = " ";

    public People()
    {
        firstname = "First Name";
        lastname = "Last Name";
    }

    public People(String firnam, String lasnam)
    {
        firstname = firnam;
        lastname = lasnam;
    }

    public String toString()
    {
        String str = firstname+" "+lastname;

        return str;
    }

} 

Names.java:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Names
{
    public static void main(String[]args)
    {
        String a = " ";
        String b = "empty";
        String c = "empty";
        int counter = 0;


        People[]peoplearray=new People[5];

        try
        {
            File names = new File("name.txt");
            Scanner read = new Scanner(names);

            while(read.hasNext())
            {
                a = read.next();
                StringTokenizer token = new StringTokenizer("!", a);

                while(token.hasMoreTokens())
                {
                b = token.nextToken();
                c = token.nextToken();
                People p = new People(b,c);
                peoplearray[counter]=p;
                ++counter;
                }
            }
        }

        catch(IOException ioe1)
        {
            System.out.println("There was a problem reading the file.");
        }

        System.out.println(peoplearray[0]);

    }
}

正如我在程序中显示的那样,我试图打印peoplearray [0]的值,但是当我这样做时,我的输出显示为:“null”。

如果程序工作正常,则peoplearray [0]的值应为“John Doe”,因为这些是“names.txt”中的适当值

peoplearray [0]的值是否应为null? 如果没有,我该怎么做才能解决这个问题? 谢谢!

1 个答案:

答案 0 :(得分:1)

你的论点的顺序是错误的:

StringTokenizer token = new StringTokenizer("!", a);

根据API constructor

  

public StringTokenizer(String str,String delim

使用

StringTokenizer token = new StringTokenizer(a,"!");