Question

In: Computer Science

I just finished this program where the program reads a text file of full names ,...

I just finished this program where the program reads a text file of full names , first and last name, and a zip code. It reads the items then stores the first name and last name and zipcodes as an objects and prints the items.   However, when i use my text file i get this error

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 "

I notice this issue only happens when the names are formatted by tabs inbetween. For example:

"Firstname Lastname 90210" <-- this prints normally because there is only a space in between each value

"Firstname (tab) Lastname (tab) 90210" <--- Does not print because of the tab spaces but I need it to print in this fashion!

Please help me fix this annoying issue! Thank you!

Please remember the names are read from a txt file thats been pre-created. Not user inputted values.

import java.io.*;
class Details//stores the firstname, lastname and zip
{
   String firstname, lastname, zip;
   public Details(String a, String b, String c)//constructor
   {
       firstname = a;lastname = b;zip = c;
   }
   public String getFirstName()//getter methods
   {
       return firstname;
   }
   public String getLastName()
   {
       return lastname;
   }
   public String getZip()
   {
       return zip;
   }
}
public class A {

   public static void main(String[] args)

   {
       Details details[] = new Details[25];int i=0;
     
       BufferedReader reader;
    
       try
       {
           reader = new BufferedReader(new FileReader("myfile.txt"));//reader object for file
           String line = reader.readLine();//read next line
           while (line != null) {
               // read next line
               String[] res = line.split(" ");//split the line according to spaces and store it in res
               details[i++] = new Details(res[0], res[1], res[2]);//create a details object with the individual strings as parameters
               line = reader.readLine();//read next line
       }
           reader.close();
       }
     
       catch (IOException e)
       {
           e.printStackTrace();
       }
     
       System.out.println("FirstName LastName ZIP");
     
       for(int j=0;j<i;j++)//display the contents of objects
       {
           System.out.println(details[j].getFirstName() + "\t " + details[j].getLastName() + "\t " + details[j].getZip());
       }
   }
}

Solutions

Expert Solution

Please find the code below.

We just have to modify Line number 37 at split(" ") to split("\\s+) . It is a regex and it tells that More than one space will be used as a split condition.

SOURCE CODE:

*Please follow the comments to better understand the code.

**Please look at the Screenshot below and use this code to copy-paste.

***The code in the below screenshot is neatly indented for better understanding.


import java.io.*;
class Details//stores the firstname, lastname and zip
{
    String firstname, lastname, zip;
    public Details(String a, String b, String c)//constructor
    {
        firstname = a;lastname = b;zip = c;
    }
    public String getFirstName()//getter methods
    {
        return firstname;
    }
    public String getLastName()
    {
        return lastname;
    }
    public String getZip()
    {
        return zip;
    }
}
public class A {

    public static void main(String[] args)

    {
        Details details[] = new Details[25];int i=0;

        BufferedReader reader;

        try
        {
            reader = new BufferedReader(new FileReader("myfile.txt"));//reader object for file
            String line = reader.readLine();//read next line
            while (line != null) {
                // read next line
                String[] res = line.split("\\s+");//split the line according to one or more \\s+ regexspaces and store it in res
                
                details[i++] = new Details(res[0], res[1], res[2]);//create a details object with the individual strings as parameters
                line = reader.readLine();//read next line
            }
            reader.close();
        }

        catch (IOException e)
        {
            e.printStackTrace();
        }

        System.out.println("FirstName LastName ZIP");

        for(int j=0;j<i;j++)//display the contents of objects
        {
            System.out.println(details[j].getFirstName() + "\t " + details[j].getLastName() + "\t " + details[j].getZip());
        }
    }
}

============

SAMPLE OUTPUT:

File

OUTPUT:


Related Solutions

Write a C program that Reads a text file(any file)  and writes it to a binary file....
Write a C program that Reads a text file(any file)  and writes it to a binary file. Reads the binary file and converts it to a text file.
Write a program that reads a file called document.txt which is a text file containing an...
Write a program that reads a file called document.txt which is a text file containing an excerpt from a novel. Your program should print out every word in the file that contains a capital letter on a new line to the stdout. For example: assuming document.txt contains the text C++
Write a simple text-formating.cpp file that reads (asks for then reads) a text file and produces...
Write a simple text-formating.cpp file that reads (asks for then reads) a text file and produces another text file in Which blank lines are removed, multiple blanks are replaced with a single blank, and no lines are longer than some given length (let say 80). Put as many words as possible on the same line (as close as possible to 80 characters). You will have to break some lines of the given file, but do not break any words or...
You are given a text file containing a short text. Write a program that 1. Reads...
You are given a text file containing a short text. Write a program that 1. Reads a given text file : shortText.txt 2. Display the text as it is 3. Prints the number of lines 4. Prints the occurences of each letter that appears in the text. [uppercase and lowercase letter is treated the same]. 5. Prints the total number of special characters appear in the text. 6. Thedisplayofstep3,4and5aboveshouldbesaveinanoutputfile:occurencesText.txt write it in C++ programing Language
C++ Write a program that reads candidate names and numbers of votes in from a file....
C++ Write a program that reads candidate names and numbers of votes in from a file. You may assume that each candidate has a single word first name and a single word last name (although you do not have to make this assumption). Your program should read the candidates and the number of votes received into one or more dynamically allocated arrays. In order to allocate the arrays you will need to know the number of records in the file....
Write the programs in JavaScript: Write a program that reads a text file and outputs the...
Write the programs in JavaScript: Write a program that reads a text file and outputs the text file with line numbers at the beginning of each line.
Write a C++ program that reads a string from a text file and determines if the...
Write a C++ program that reads a string from a text file and determines if the string is a palindrome or not using stacks and queue
Python program: Write a program that reads a text file named test_scores.txt to read the name...
Python program: Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for 3 tests. The program should display class average for first test (average of scores of test 1) and average (average of 3 tests) for each student. Expected Output: ['John', '25', '26', '27'] ['Michael', '24', '28', '29'] ['Adelle', '23', '24', '20'] [['John', '25', '26', '27'], ['Michael', '24', '28', '29'], ['Adelle', '23', '24', '20']] Class average for test 1...
Could you write a c- program that reads a text file into a linked list of...
Could you write a c- program that reads a text file into a linked list of characters and then manipulate the linked list by making the following replacements 1. In paragraph 1 Replace all “c” with “s” if followed by the characters “e”, “i” or “y”; otherwise 2. In pragraph 2 Replace "We" with v"i" This is the text to be manipulated: Paragraph1 She told us to take the trash out. Why did she do that? I wish she would...
● Write a program that reads words from a text file and displays all the words...
● Write a program that reads words from a text file and displays all the words (duplicates allowed) in ascending alphabetical order. The words must start with a letter. Must use ArrayList. MY CODE IS INCORRECT PLEASE HELP THE TEXT FILE CONTAINS THESE WORDS IN THIS FORMAT: drunk topography microwave accession impressionist cascade payout schooner relationship reprint drunk impressionist schooner THE WORDS MUST BE PRINTED ON THE ECLIPSE CONSOLE BUT PRINTED OUT ON A TEXT FILE IN ALPHABETICAL ASCENDING ORDER...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT