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...
In C++, write a program that reads data from a text file. Include in this program...
In C++, write a program that reads data from a text file. Include in this program functions that calculate the mean and the standard deviation. Make sure that the only global variables are the actual data points, the mean, the standard deviation, and the number of data entered. All other variables must be local to the function. At the top of the program make sure you use functional prototypes instead of writing each function before the main function... ALL LINES...
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
Write a program that reads a text file and reports the total count of words of...
Write a program that reads a text file and reports the total count of words of each length. A word is defined as any contiguous set of alphanumeric characters, including symbols. For example, in the current sentence there are 10 words. The filename should be given at the command line as an argument. The file should be read one word at a time. A count should be kept for how many words have a given length. For example, the word...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT