Reading data from a file to an object? - java

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();
}
}

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.

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

You can't directly assign a string line to an object, you need to parse the line into parts and assign values to variables one by one.

How is your input text organized? The Scanner's nextLine() method is returning a String object and definitely you cannot assign that to a type Flight. There are different methods to get the different values in the Scanner like nextInt(), nextFloat().
Basically you can try like this
Flight myFlight = new Flight();
myFlight.setFlightName(inputFile.next());
myflight.setMiles(inputFile.nextInt();
etc.
This is just a sample, you need to check the format you have in the input.txt file.

Related

How to take multiple lines of input

If I copy and paste into a program It only takes the first line for instance I copy a few blocks from Microsoft Excel and Paste it pastes the codes like this:
72LYY-785B9-0WQD9
88CXK-4E8BB-TA2GD
JLEIZ-0KYKP-PY2E4
LV5TL-A6CLB-P59GX
My program only takes 72LYY-785B9-0WQD9, but I want the scanner to take all until it is empty.
I am using
String userData = takeInput.nextLine();
I put it into a String and then turn it into an array of chars.
Any help?
Did you try any other approach?
Scanner stdin = new Scanner(new BufferedInputStream(System.in));
while (stdin.hasNext()) {
System.out.println(stdin.nextLine());
}

Reading a file using Scanner

I'm having some trouble understanding how Java uses Scanner to read lines from a file and was hoping to get some clarification after days of confusion.
I have a .txt file with one line that contains a name and then 5 doubles. I'm trying to figure out how I can assign each of those to a variable inside a loop so I can work with the data. My goal is to actually take the data from these lines and pass them as parameters to another method for validation, so if there's an easier way to do that, I'm all ears. I feel like I can't find a way to just iterate over each thing inside the nextLine, just over the entire line itself. I'm trying to do this without using an array, here's the relevant code snippet I have right now.
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
String line = "";
accumulator++;
Scanner split = new Scanner(inputFile.nextLine());
while (split.hasNext())
{
}
stockName = inputFile.next();
shares = inputFile.nextDouble();
purchasePrice = inputFile.nextDouble();
purchaseCommission = inputFile.nextDouble();
salesPrice = inputFile.nextDouble();
salesCommission = inputFile.nextDouble();
System.out.println(stockName);
System.out.println(shares);
System.out.println(purchasePrice);
System.out.println(purchaseCommission);
System.out.println(salesPrice);
System.out.println(salesCommission);
System.out.print(line);
System.out.println("");
// checkValidity(line);
}
I'm having a hard time asking and articulating what I don't know, so any and all help is greatly appreciated... I've literally been working on this for three days and I'm at a total wall.
EDIT:
The layout of the text file looks like this
DELL: Dell Inc
125 25.567 0.025 28.735 0.025
MSFT: Microsoft
34.1 -15.75 0.012 15.90 0.013
You are almost there. You need to just remove the line:
while (split.hasNext())
{
}
This consumes all the elements given to split. You need to assign this to all the elements like stock, salesPrice etc.
So, the new snippet inside the outer while loop is
stockName = inputFile.nextLine();
Scanner split = new Scanner(inputFile.nextLine());
shares = split.nextDouble();
purchasePrice = split.nextDouble();
purchaseCommission = split.nextDouble();
salesPrice = split.nextDouble();
salesCommission = split.nextDouble();
Since, you are reading line by line, also make sure the outer while loop looks like:
while (inputFile.hasNextLine()) {
}

How can you delay object creation until you have read in all parameters?

I'm trying to solve a problem with creating a custom object with multiple parameters, but the parameters have to first be found one by one using a Scanner.
So basically, given an input file, where each line will represent a new object with multiple attributes (a county with its name, its crime index, etc.), I am using a Scanner with a while loop to scan the input file line by line, and then within that loop I'm using another while loop and a new Scanner that then scans each word within the line. That way, I can separate all of the object-to-be's attributes and then create the object by passing all of those values into the constructor.
What I can't figure out is how to delay the creation of the object until I have every word in each line, since every line in the input file is to be made into an object, with every word in that line being used as a parameter for the object.
Does anyone know how this can be done effectively without having to store all the words into an array or something like that?
Here's the constructor from the object class that will take all of the words of a line, which are all in proper order, and create a new object for each line in the input file:
public CountyItem(String countyName, String countyState, double countyPercentageClintonVoters, double countyResidentMedianAge,
int countyResidentMeanSavings, int countyPerCapitaIncome, double countyPercentageBelowPovertyLevel,
double countyPercentageVeterans, double countyPercentageFemale, double countyPopulationDensity,
double countyPercentageLivingInNursingHomes, int countyCrimeIndexPerCapita){
itemCountyName = countyName;
itemCountyState = countyState;
itemCountyPercentageClintonVoters = countyPercentageClintonVoters;
itemCountyResidentMedianAge = countyResidentMedianAge;
itemCountyResidentMeanSavings = countyResidentMeanSavings;
itemCountyPerCapitaIncome = countyPerCapitaIncome;
itemCountyPercentageBelowPovertyLevel = countyPercentageBelowPovertyLevel;
itemCountyPercentageVeterans = countyPercentageVeterans;
itemCountyPercentageFemale = countyPercentageFemale;
itemCountyPopulationDensity = countyPopulationDensity;
itemCountyPercentageLivingInNursingHomes = countyPercentageLivingInNursingHomes;
itemCountyCrimeIndexPerCapita = countyCrimeIndexPerCapita;
}
And here's my program's main method (still unfinished of course) that shows what I'm talking about with my plan to use nested while loops and two separate scanners to first read every line in the input file and then every word in that line:
public static void main(String[] args) throws IOException{
//Scanner and FileWriter
Scanner inFile = new Scanner(new FileReader("data/test1.txt")); //change this to use different test .txt file
FileWriter outFile = new FileWriter("data/output.txt");
//loops through each line in inputl.txt until end is reached
while(inFile.hasNextLine()){
String line = inFile.nextLine();
Scanner lineScanner = new Scanner(line);
//loops through every word in a given line
while(lineScanner.hasNext()){
}
lineScanner.close();
}
inFile.close();
}
You can use the builder pattern to slowly build up your constructor's dependencies, or you could also just introduce another constructor that takes in a File, and you can move all the logic from your main method into that constructor.

How do I set the field variables in a method to data being read in from a .txt file in Java?

I have my default constructor set to at the moment.
//Default constructor
public MyInfo(String args) {
Name = "";
DateOfBirth = "";
Location = "";
AvgTemp = 0;
}
Since I am not sure what your actual .txt file looks like im going to assume that each line has Name,DateOfBirth,Location,AvgTemp.
Using a buffered reader, read the lines within a while loop and assign each value in an array after splitting the line by commas for example. Make sure to change your current variables to arrays before doing this.
BufferedReader br = new BufferedReader(new FileReader("Filename.txt"));
while (somevariable!=null){
somevairable=br.readLine();
String[] parts = somevariable.split(",");
Names[x]=parts[1]
And I will leave the rest up to you. Hopefully this is a decent start and you can follow the instructions. I suggest reading up on different types of file and buffered readers and writers.

Adding to an object array list using a file reader

Basically I have to classes interacting with one another in this situation one company and one the driver, this code is written in the driver. So I am using a file reader to scan a text file that looks like this with a space between each line.
John:Smith:Manufacturing:6.75:120:444
Betty:White:Manager:1200.00:111
Stan:Slimy:Sales:10000.00:332
Betty:Boop:Design:12.50:50:244
And the code is as follows. The addEmployee method of the company class has a (string, string, string, double, int, int) parameter. The text file it reads in has a colons inbetween each part, so howe can I add it to the arraylist of objects. And keep going until all of them are read. Sorry if my questions difficult to understand, if you want me to elaborate let me know in the comments. I just didn't want to make the question too long.
else if (e.getSource()==readButton){
JFileChooser fileChooser = new JFileChooser("src");
if (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
empFile=fileChooser.getSelectedFile();
}
Scanner scan = new Scanner("empFile");
while(scan.hasNext()){
scan.next().split(":");
if (position.equals("Manager")){
c.addEmployee(fName, lName, position2, Double.parseDouble(firstParam2), 0, Integer.parseInt(empNum2));
}
else if(position.equals("Sales")){
c.addEmployee(fName, lName, position2, Double.parseDouble(firstParam2), 0, Integer.parseInt(empNum2));
}
else{
c.addEmployee(fName, lName, position2, Double.parseDouble(firstParam2), Integer.parseInt(secondParam2), Integer.parseInt(empNum2));
}
}
This line:
scan.next().split(":");
Will return an array of Strings that you're not storing anywhere. Turn it into:
String[] rowData = scan.next().split(":");
And use every item in the array as you wish, for example to fill your variables or directly as arguments for your class constructor. Providing a sample of the former:
fName = rowData[0];
lName = rowData[1];
position = rowData[2];
firstParam2 = rowData[3];
secondParam2 = rowData[4];
empNum2 = rowData[5];

Categories