Zampanò
Zampanò

Reputation: 594

Error Reading Files to Store their Data in an Array

The program that I am writing is in Java. I am attempting to make my program read the file "name.txt" and store the values of the text file in an array.

So far I am using a text file that will be read in my main program, a service class called People.java which will be used as a template for my program, and my main program called Names.java which will read the text file and store its values into an array.

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]);

    }
}

As I show in my program, I tried to print the value of peoplearray[0], but when I do this, my output reads: "null."

If the program were working corrrectly, the value of peoplearray[0] should be, "John Doe" as those are the appropriate values in "names.txt"

Is the value of peoplearray[0] supposed to be null? If not, what can I do to fix this problem? Thanks!

Upvotes: 1

Views: 53

Answers (1)

Ramanlfc
Ramanlfc

Reputation: 8354

The order of your arguments is wrong:

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

According to API constructor

public StringTokenizer(String str, String delim)

use

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

Upvotes: 1

Related Questions