reading text file

hi. just wondering if someone can help me. i need to find out how to read a text ascii file and then print out whats in the file as an array of 10 objects in reverse order using tokenizer. the file contain car make and their speed. and look a bit like this in the text file.

fiatpunto         90
fordescort       100
hondacivic       110 etc.

i need to get this file and then print it out in reverse order using arrays.
i have already done the code to retrieve the file, but it's all jumbled up when its shows.this is because i cant figure out how to collect each line as an array. would be gratefull for any help on this.

this is the code i have got so far.

import java.io.*;
import java.util.*;

public class ReadCarFile
{
 //text file characters
 static BufferedReader fileInput;

 //collect input from user
 static BufferedReader keyboard =
        new BufferedReader(new InputStreamReader(System.in));

 public static void main(String Args[]) throws IOException
 {
  int speed;
  String textLine,filecar, car;
  boolean moreToRead = true, fileNotFound;
  StringTokenizer tokens;
 

  //find and open file
  do
  {
   fileNotFound =false;
   System.out.print("File to be read ? "); System.out.flush();
   filecar = keyboard.readLine();
   try
   {
    fileInput = new BufferedReader( new FileReader(filecar));
   }
   catch(FileNotFoundException e)// exception handling if file is not found
   {
    System.out.println("File not found " + e.toString());
    fileNotFound = true;
   }
  } while(fileNotFound);
 
  // input from the file
  textLine =  fileInput.readLine(); // format strings
  moreToRead = (textLine != null);
  while(moreToRead)
  {
     
      tokens = new StringTokenizer(textLine);
      car = tokens.nextToken();
      speed = Integer.parseInt(tokens.nextToken());
     
      System.out.print(car +""+speed);
     
     
    // output the values to screen
    System.out.println(textLine);
   // input from the file    
    textLine =  fileInput.readLine(); // Unicode format strings
    moreToRead = (textLine != null);
  }
  // Close
  fileInput.close();
  System.out.println("File read and closed");
 }



jayjjAsked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
no classes and variable are different things.
0
 
objectsCommented:
your read loop would be simpler as:

while (null!=(textLine=in.readLine()))
{
   ...
}
0
 
objectsCommented:
A collection would be easier than an array to store lines

ArrayList list = new ArrayList();
while (null!=(textLine=fileInput.readLine()))
{
   list.add(textLine);
}
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
objectsCommented:
then you can gio thru the lines in reverser order:

for (int i=list.size()-1; i>=0l i--)
{
    tokens = new StringTokenizer((String)list.get(i));

      car = tokens.nextToken();
      speed = Integer.parseInt(tokens.nextToken());
     
      System.out.print(car +""+speed);
}
0
 
jayjjAuthor Commented:
i have to use array and string tokenizer
0
 
objectsCommented:
String[] list = new String[100];
int count = 0;
while (null!=(textLine=fileInput.readLine()))
{
   list[count++] = textLine;
}
for (int i=list.length-1; i>=0; i--)
{
    tokens = new StringTokenizer(list[i]);

      car = tokens.nextToken();
      speed = Integer.parseInt(tokens.nextToken());
     
      System.out.print(car +""+speed);
}
0
 
jayjjAuthor Commented:
String[] list = new String[100];

on this line here would i have to change the String[100] to String[10] to hold my ten objects?
0
 
objectsCommented:
that sets up the size of the array, you'd need to change that to the most lines that need to be stored.

> for (int i=list.length-1; i>=0; i--)

a little correction, this line should be:

for (int i=count-1; i>=0; i--)


0
 
jayjjAuthor Commented:
this is my version so far. there is an error with the StringTokenizer((String)list.get(i)); line.
import java.io.*;
import java.util.*;

public class ReadCarFile
{
 //sequential text file input of characters
 static BufferedReader fileInput;

 //keyboard input
 static BufferedReader keyboard =
        new BufferedReader(new InputStreamReader(System.in));

 public static void main(String Args[]) throws IOException
 {
  int speed;
  String textLine,filecar, car;
  boolean moreToRead = true, fileNotFound;
  StringTokenizer tokens;
  String[] list = new String[100];
  int count = 0;
 

  //open the file
  do
  {
   fileNotFound = false;
   System.out.print("File to be read ? "); System.out.flush();
   filecar = keyboard.readLine();
   try
   {
    fileInput = new BufferedReader( new FileReader(filecar));
   }
   catch(FileNotFoundException e)// if file is not found
   {
    System.out.println("File not found " + e.toString());
    fileNotFound = true;
   }
  } while (null!=(textLine=fileInput.readLine()));

 
       {
   list[count++] = textLine;
      }

 
 
 
  for (int i=count-1; i>=0; i--)

  {
     
      tokens = new StringTokenizer((String)list.getlist(i));
      car = tokens.nextToken();
      speed = Integer.parseInt(tokens.nextToken());
     
      System.out.print(car +""+speed);
     
     
    // output the values
    System.out.println(textLine);
   // input from the file    
    textLine =  fileInput.readLine();
    moreToRead = (textLine != null);
  }
  // Close
  fileInput.close();
  System.out.println("File read and closed");
 }
}

0
 
objectsCommented:
should be:

    tokens = new StringTokenizer(list[i]);
0
 
jayjjAuthor Commented:
ok i changed the line it complied no errors but now its cannt find the file that it must display
0
 
objectsCommented:
that code hasn't changed has it?
are you running from the same directory
0
 
jayjjAuthor Commented:
yes i am running from the same directory. i changed that line you said. but it cannt find the file.
0
 
objectsCommented:
None of the changes I suggested affected oponing the file.
Check the filename you enter does exist.
0
 
jayjjAuthor Commented:
it does exist. could it be that its because of changing of editors why this is happening? changed from bluej to jcreator
0
 
jayjjAuthor Commented:
i think it must be my program. i will try it tommorow on another computer and then see what happen then i will get back to you.
0
 
objectsCommented:
if you're not typing the full path of the file yes.
If you only type the filename then it will look in the directory it is being run from which could well be different when running from different ide.
see if you can set the directory to run the class from.
0
 
jayjjAuthor Commented:
ok now it stop showing the exception it just keep asking to enter the file but shows nothing.
0
 
jayjjAuthor Commented:
it seems to be finding the file but not showing it because it has stop showing the exeption error. but if i enter the wrong file name the error come on.
0
 
objectsCommented:
>  } while (null!=(textLine=fileInput.readLine()));
>      {
>   list[count++] = textLine;
>     }

you've got your loops mixed up.
should be:

  } while(fileNotFound);

  while (null!=(textLine=fileInput.readLine()))
  {
     list[count++] = textLine;
  }
0
 
jayjjAuthor Commented:
sorry i am still getting errors after adding this other while. i think the reason its not showing the file is because nothing is going into the loop.
0
 
jayjjAuthor Commented:
ok this is the new code but it keep. throwing exception about a pointer when i try to search for the file.


import java.io.*;
import java.util.*;

public class ReadCarFile
{
 //sequential text file input of characters
 static BufferedReader fileInput;

 //keyboard input
 static BufferedReader keyboard =
        new BufferedReader(new InputStreamReader(System.in));

 public static void main(String Args[]) throws IOException
 {
  int speed;
  String textLine,filecar, car;
  boolean moreToRead = true, fileNotFound;
  StringTokenizer tokens;
  String[] list = new String[1];
  int count = 0;
 

  //open the file
  do
  {
   fileNotFound = false;
   System.out.print("File to be read ? "); System.out.flush();
   filecar = keyboard.readLine();
   try
   {
    fileInput = new BufferedReader( new FileReader(filecar));
   }
   catch(FileNotFoundException e)// if file is not found
   {
    System.out.println("File not found " + e.toString());
    fileNotFound = true;
   }
  } while(fileNotFound);
 
 
  while (null!=(textLine=fileInput.readLine()));

 
       {
   list[count++] = textLine;
      }

 
 
 
  for (int i=count-1; i>=0; i--)

  {
     
      tokens = new StringTokenizer(list[i]);

      car = tokens.nextToken();
      speed = Integer.parseInt(tokens.nextToken());
     
      System.out.print(car +""+speed);
     
     
    // output the values
    System.out.println(textLine);
   
   
   // input from the file    
    textLine =  fileInput.readLine();
    moreToRead = (textLine != null);
  }
  // Close
  fileInput.close();
  System.out.println("File read and closed");
 }
}

0
 
objectsCommented:
what exception?
0
 
jayjjAuthor Commented:
File to be read ? Cities.txt
Exception in thread "main" java.lang.NullPointerException
        at java.util.StringTokenizer.<init>(StringTokenizer.java:122)
        at java.util.StringTokenizer.<init>(StringTokenizer.java:152)
        at ReadAsciiFile.main(ReadAsciiFile.java:64)
Press any key to continue...
0
 
jayjjAuthor Commented:
ok i got back my original code from the start an just made the changes you suggested and it still have to same error.


import java.io.*;
import java.util.*;

public class ReadAsciiFile
{
 //sequential text file input of characters
 static BufferedReader fileInput;

 //keyboard input
 static BufferedReader keyboard =
        new BufferedReader(new InputStreamReader(System.in));

 public static void main(String Args[]) throws IOException
 {
  int speed;
  String textLine,filecar, car;
  boolean moreToRead = true, fileNotFound;
  StringTokenizer tokens;
  String[] list = new String[10];
  int count = 0;
 

  //open the file
  do
  {
   fileNotFound = false;
   System.out.print("File to be read ? "); System.out.flush();
   filecar = keyboard.readLine();
   try
   {
    fileInput = new BufferedReader( new FileReader(filecar));
   }
   catch(FileNotFoundException e)// if file is not found
   {
    System.out.println("File not found " + e.toString());
    fileNotFound = true;
   }
  } while(fileNotFound);
 
 
 
 while (null!=(textLine=fileInput.readLine()))
{
   list[count++] = textLine;
}
 
 
 
 
  // input from the file
  textLine =  fileInput.readLine(); // Unicode format strings
  moreToRead = (textLine != null);
 
  for (int i=list.length-1; i>=0; i--)
  //while(moreToRead)
  {
     
      tokens = new StringTokenizer(list[i]);
      car = tokens.nextToken();
      speed = Integer.parseInt(tokens.nextToken());
     
      System.out.print(car +""+speed);
    // output the values read to the screen
    System.out.println(textLine);
   // input from the file    
    textLine =  fileInput.readLine(); // Unicode format strings
    moreToRead = (textLine != null);
  }
  // Close
  fileInput.close();
  System.out.println("File read and closed");
 } // end of main
} // end of class ReadAsciiFile


0
 
objectsCommented:
a couple of problems, theres a semicolon after the while loop reading the file
should be:

while (null!=(textLine=fileInput.readLine()))
{
   list[count++] = textLine;
}

And you read the file in the final loop. thats not needed as the file has already been read,
should be:
 
 
for (int i=count-1; i>=0; i--)
{
      tokens = new StringTokenizer(list[i]);

      car = tokens.nextToken();
      speed = Integer.parseInt(tokens.nextToken());
     
      System.out.print(car +""+speed);
     
     
    // output the values
    System.out.println(textLine);
 }
0
 
jayjjAuthor Commented:
ok it now reads the file but why does it print it line this......

fiat90null
ford120null

instead of

fiat   90
ford  120
0
 
jayjjAuthor Commented:
why didnt the tokenizer split it
0
 
objectsCommented:
tokenizer did split it, you println() doesn't put a space between them

try:

for (int i=count-1; i>=0; i--)
{
      tokens = new StringTokenizer(list[i]);

      car = tokens.nextToken();
      speed = Integer.parseInt(tokens.nextToken());
     
      System.out.print(car +"    "+speed);
 }
0
 
jayjjAuthor Commented:
why does it print the word null beside each one??
0
 
objectsCommented:
that was being caused by the line:

   // output the values
    System.out.println(textLine);

That should be removed, it is no longer used
0
 
jayjjAuthor Commented:
if i remove that line it will print the text accross the screen instead of going down.
0
 
jayjjAuthor Commented:
ok i got it now
0
 
jayjjAuthor Commented:
just one more thing how do i work out the average of the speeds?? i got this code so far but it have problems.

static double averagespeed(speed list[])
    {
        int total = 0;
        for (int i=0; i <list.length; i ++)
        total = total + list[i].getTemp();
       
        return (double) total/list.length;
       
    }
0
 
jayjjAuthor Commented:
static double averagespeed(speed list[])
    {
        int total = 0;
        for (int i=0; i <list.length; i ++)
        total = total + list[i].getspeed();
       
        return (double) total/list.length;
       
    }
0
 
objectsCommented:
try:

static double averagespeed(speed list[])
    {
        int total = 0;
        for (int i=0; i <list.length; i ++)
        total = total + list[i].getspeed();
       
        return (double) total/ (double) list.length;
       
    }
0
 
jayjjAuthor Commented:
i keep getting this error, speed has already decleared

--------------------Configuration: JDK version 1.3 <Default>--------------------
ReadAsciiFile.java:79: cannot resolve symbol
symbol  : class speed  
location: class ReadAsciiFile
 static double averagespeed(speed list[])
                           ^
1 error

Process completed.

0
 
objectsCommented:
where is your speed class defined?
0
 
jayjjAuthor Commented:
public static void main(String Args[]) throws IOException
 {
  int speed;      
0
 
objectsCommented:
thats not a class, thats a variable name.
0
 
jayjjAuthor Commented:
but isnt it already set as a variable and cannt be set as a class
0
 
jayjjAuthor Commented:
thanks for your help with this
0
 
objectsCommented:
no worries :)
0
All Courses

From novice to tech pro — start learning today.