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

时间:2015-11-26 06:38:53

标签: java arrays object java.util.scanner 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;
        }
}

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]的值,但是当我这样做时,我的输出显示为:“empty empty”,这是我在实例化时给出的字符串b和字符串c的值它们。

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

我该怎么做才能解决这个问题?

谢谢!

2 个答案:

答案 0 :(得分:0)

  

StringTokenizer(String str,String delim)

是StringTokenizer的构造函数。

你写错了。
只需改变你的路线 StringTokenizer token = new StringTokenizer("!", a);

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

答案 1 :(得分:0)

稍微改变一下

        StringTokenizer token = new StringTokenizer(a, "!");
        while(token.hasMoreTokens())
        {
             b = token.nextToken();
             c = token.nextToken();
        }
        //do something with them