Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from a file to an object?

Ok another question about my program that I'm writing called "Flight." In my tester I am creating an object from the Flight class called myFlight. The object has several fields (flight name, miles traveled, etc) but what I'm doing is reading the data from a file called input.txt and trying to put it into the object that I created. There are five lines of information on the file that I'm reading. For some reason I can't quite get it right, if anyone could help me fix this problem I would greatly appreciate it.

Here is the Constructor that has all the fields from my Flight class:

 public Flight(String name, int num, int miles, String origin, String destination)
  {
    Airlinename = name;
    flightnumber = num;
    numofmiles = miles;
    Origincity = origin;
    Destinationcity = destination;
  }

And the part of my program where I created the object and try to read the data from the file. I had created a blank constructor in my class too because I wasn't sure if I was supposed to put anything in the object when I created it.

Flight myFlight = new Flight();

    File myFile = new File("input.txt");
    Scanner inputFile = new Scanner(myFile);

    while (inputFile.hasNext())
    {
      myFlight = inputFile.nextLine();
    }

    inputFile.close();
  }
}
like image 282
Andrew Avatar asked Mar 14 '26 05:03

Andrew


1 Answers

Just in case you use special characters, you need to modify your program so you can read them correctly.

Scanner inputFile = new Scanner(myFile, "UTF-8");

On the other hand, if the text file contains the following, possibly subsequent calls to nextInt() generate a runtime exception.

Gran España
1
1001
New York
Los Angeles

If that were the case, the reading should be different.

myFlight = new Flight(inputFile.nextLine(), 
           Integer.parseInt(inputFile.nextLine()), 
           Integer.parseInt(inputFile.nextLine()), 
           inputFile.nextLine(), 
           inputFile.nextLine());

As with any program, when adding more conditions to improve the model, it needs more and more code.

Good luck.

like image 98
Paul Vargas Avatar answered Mar 17 '26 02:03

Paul Vargas