Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

[HOMEWORK] Error Reading Files to Store their Data in an Array

array object file stringtokenizer scanner

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1 bodette


    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 26 November 2015 - 08:00 AM

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.




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;


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

			File names = new File("name.txt");
			Scanner read = new Scanner(names);
				a = read.next();
				StringTokenizer token = new StringTokenizer("!", a);
				b = token.nextToken();
				c = token.nextToken();
				People p = new People(b,c);
		catch(IOException ioe1)
			System.out.println("There was a problem reading the file.");

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"

What can I do to fix this problem?


Edited by bodette, 26 November 2015 - 08:11 AM.

#2 wim DC

wim DC


  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts

Posted 27 November 2015 - 12:35 PM

Scanner already has some kind of "StringTokenizer" functionality inside it.


You can make your life a lot easier if you know how to use it. It's called the "delimiter" for Scanner:

String input = "John!Doe\r\nJane!Doe\r\nMike!Smith\r\nJohn!Smith\r\nGeorge!Smith";
Scanner scanner = new Scanner(input);
People[] peoplearray = new People[5];
int counter = 0;

while(scanner.hasNext()) {
	peoplearray[counter++] = new People(scanner.next(), scanner.next());
	if( scanner.hasNextLine()) 
		scanner.nextLine(); //read and ignore the [ENTER] in files

for (People people : peoplearray) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download