Reading data from file to object?

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

Here is a 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 also created an empty constructor in my class, because I was not sure if I should 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();
  }
}
+3
source share
4 answers

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

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

On the other hand, if the text file contains the following, perhaps subsequent calls nextInt()will throw an exception at runtime.

Gran España
1
1001
New York
Los Angeles

If so, 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 additional conditions are added to improve the model, it needs more and more code.

Good luck.

+1
source

to try

myFlight = new Flight(inputFile.next(), inputFile.nextInt(), 
           inputFile.nextInt(), inputFile.next(), inputFile.next());
0
source

, .

0

How is your introductory text organized? The Scanner method nextLine()returns a String object, and you definitely cannot assign it to a Flight type. There are different ways to get different values ​​in a scanner, for example nextInt(), nextFloat().

Basically, you can try how to do it.

Flight myFlight = new Flight();
myFlight.setFlightName(inputFile.next());
myflight.setMiles(inputFile.nextInt();

and etc.

This is just a sample, you need to check the format that you have in the input.txt file.

0
source

All Articles