Creating Separate Objects with Loops - java

I'm creating a race results program and I need to store all the info from a text file that looks like this:
------1 Jackson Bertoli 11 Jasper 15.29-----------------------------------------------------------------------------------------
As you can see, it contains the place, a first name, a last name, a grade, a school name, and a time.
This information needs to be stored together, so I figured the best way to do this was storing it in an object "runner", and then putting all of those "runner" objects inside an arraylist. The only problem with this is that I can't find how to make a different object name for each object in my while loo (which is going through each line to read the elements from the text file) for each separate runner. Is it even necessary to have a different object name for each object? And if I am allowed to have many separate objects with the same name, how do I distinguish them apart? Here's a bit of the code behind it
public void readfile() {
while (initialresults.hasNext()){
strplace = initialresults.next();
dataplace = Integer.parseInt(strplace);
datafirstname = initialresults.next();
datalastname = initialresults.next();
strgrade = initialresults.next();
datagrade = Integer.parseInt(strgrade);
dataschool = initialresults.next();
strorigtime = initialresults.next();
dataorigtime = Double.parseDouble(strorigtime);
runner newrunner = new runner(datafirstname,datalastname, datagrade, dataschool, dataorigtime);
amountofrunners.add(newrunner);
counter++;
}
}
So you can see I'm reading each element from the text file, and then trying to make a new "runner" object, store those elements from the text file in that object, but then I'm stuck putting the next line's elements in that same object name. How can I create a new object name every time to store those elements in? The only reason I'm using an object is because it seems like the best way to keep data organized for a runner. But if I used an array or a list, wouldn't that get disorganized and difficult to sort through? Thank you for your help in advance.

When your loop runs, even though the runner class is being used multiple times, it creates a new (and different) runner object each time the loop iterates (runs through a cycle).
In the line amountofrunners.add(newrunner);, Java basically copies the value(s) stored in newrunner and stores it/them seperately. Every object is different in this case, even if it has the same variable name when it's created.
Using an ArrayList actually makes it easier to sort through because you can use indexes, foreach loops, and other features to help manage the objects stored in the ArrayList.

I think you were trying to do something like this:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public static class Runner{
int place;
String firstName, lastName, school;
double origTime, grade;
Runner(int place,String firstName,String lastName,double grade,String school,double origTime){
this.place = place;
this.firstName = firstName;
this.lastName = lastName;
this.grade = grade;
this.school = school;
this.origTime = origTime;
}
}
public static List<Runner> readfile(Scanner in) {
List<Runner> runners = new ArrayList<Runner>();
while (in.hasNext()){
runners.add(new Runner(
in.nextInt(), // place
in.next(), in.next(), //first, last name
in.nextDouble(), // grade
in.next(), // school
in.nextDouble() // original time
));
}
return runners;
}
public static void main(String[] args) throws IOException {
List<Runner> runners;
try (Scanner s = new Scanner(new BufferedReader(new FileReader("file.txt")))) {
runners = readfile(s);
}
// Do something with runners
}

Related

HashMap with multiple values get.key() error

import java.util.*;
class Student{
final String name;
final String gender;
public String number;
static Map<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
static ArrayList<String> nameandNumber = new ArrayList<>();
Student(String number, String name, String gender) {
this.name = name;
this.gender = gender;
this.number = number;
nameandNumber.add(this.name);
nameandNumber.add(this.number);
hm.put(this.gender,nameandNumber);
}
void getPersonByGender() {
String[] Liste = hm.get("Man").toArray(new String[0]);
for (int i = 0; i < Liste.length - 1; i += 2) {
System.out.println(Liste[i] + "\t<------>\t" + Liste[i + 1]);
}
}
}
hello guys i am creating a class and this class will return me 10 student information which I will give (according to the difference between men and women). When i try to use getPersonByGender's function this function gives me all students.
static ArrayList<String> nameandNumber = new ArrayList<>();
new is useful: Count the amount of times your code ever invokes new ArrayList. It's a fairly easy answer: Once. For your entire program.
If you only call new once, that means there is only one list. In the whole system.
No wonder then: This:
nameandNumber.add(this.number);
is called 10 times (because 10 students) for a single 'run' of your app. Thus, that one list you have must therefore have all these numbers added together - that's why you see all the data.
Your code is, unfortunately, layers of bad design decisions.
You can 'fix' the problem (but it'll still be fragile code that is hard to read), or you can 'fix' the design (which is more work).
Fix the problem
Instead of 1 list shared by all students which obviously can't work, you want to call new ArrayList for each student. Get rid of that static single arraylist, and instead make one every time:
Student(String number, String name, String gender) {
this.name = name;
this.gender = gender;
this.number = number;
var nameandNumber = new ArrayList<String>();
nameandNumber.add(this.name);
nameandNumber.add(this.number);
hm.put(this.gender, nameandNumber);
}
Now you call new ArrayList the right number of times throughout one run of your program, for example.
But you're still in trouble here - because you decided to use a List to represent a single idea (a student), you have confused yourself: A given gender maps to multiple students. Given that a single student is represented by a List<String>, multiple students would be a List<List<String>> and, oof, this is getting real complex, real fast.
We could plug away at fixing this further but let's take a step back and fix your design instead!
Fix the design
More generally, java's typing system is highly nominal: Types have names, and the more descriptive the name, the better.
Student is a far better, clearer name than List<String>. How is a reader of your code supposed to know that those List<String> objects specifically are intended to contain precisely 2 strings, the first of which is the student's name, the second of which is their student ID number? It doesn't say that anywhere. If you mess it up you get no compiler errors of any kind.
You have a type, right there, that properly describes that concept: Student!
So why not replace this bad code:
static Map<String, ArrayList<List<String>>> hm = new HashMap<String, ArrayList<List<String>>>();
With this much improved code:
static Map<String, List<Student>> genderMap = new HashMap<>();
It has all sorts of improvements:
It has a proper name. hm doesn't mean anything.
It uses <> to be shorter - you don't need to repeat that stuff.
It codes to the principle (List) instead of the concrete class.
It uses nominal types - this maps a gender string to a list of students. And the code reads the same way, that's good.
Putting it together:
class Student {
final String name;
final String gender;
final String number;
static Map<String, List<Student>> genderMap = new HashMap<>();
Student(String number, String name, String gender) {
this.name = name;
this.gender = gender;
this.number = number;
List<Student> studentsForThisGender = genderMap.get(gender);
if (studentsForThisGender == null) {
// There is no list yet; we need to make one.
genderMap.put(gender, studentsForThisGender = new ArrayList<>());
}
studentsForThisGender.add(this);
}
static void getPersonByGender() {
Student[] liste = genderMap.get("Man").toArray(new Student[0]);
for (Student student : liste) {
System.out.println(student.name + "\t<------>\t" + student.number);
}
}
}
Note:
getPersonByGender is now static - that's a thing you do to the concept of 'students' not any particula student.
Instead of this nebulous 'print list[0] - you just sorta have to know that's the name', we print student.name which documents itself.
We fixed the problem where you were list-confused.
If you get a little further along your java studies, that 'get the list of students for a given gender, and make a new list if neccessary' can be put more succintly. The last 4 lines can be reduced to:
genderMap.computeIfAbsent(gender, () -> new ArrayList<>()).add(this);
But I bet that syntax, and what is happening there, hasn't been covered yet in your java course.

Is it possible to assign numbers to strings and then put those numbers in a dequeue system?

I'm writing some code and I would like some help with an issue to do with queue's in Eclipse.
Is there any way to assign numbers to a string of characters and then put those numbers in a dequeue system whereby the end function will tell the user the string of characters not the number and leave the head of the queue ? I have tried multiple different iterations using de_queue but nothing has seemed to work so far.Sorry if this may seem basic, I haven't had Java long. This is what the code looks like now but i understand the format will need altering. Any help is appreciated.
package britishairways;
import java.util.LinkedList;
import java.util.Queue;
public class Crew {
public static void main(String[] args) {
Queue<String> crewLine = new LinkedList<String>();
crewLine.add("Sam and Rick");
crewLine.add("Beth and Mark");
crewLine.add("Jennifer and Chris");
crewLine.add("Akshay and Ahmed");
crewLine.add("Nick and Heather");
System.out.println(crewLine.poll());
System.out.println(crewLine);
}
}
Maybe try to use a help class like.
public class LineElement{
private String names;
private int id;
public LineElement(int id, String names){
this.id = id;
this.names = names;
}
}
and then init the Queue like: Queue<LineElement> crewLine = new LinkedList<LineElement>();
and add new Elements with: crewLine.add(new LineElement(14, "Morthie and ick"));

How to Create Objects Using Records in a Text File (Java)

I'm working on a program for my Java class where I'm using a file of objects (clothing items) that represents inventory for a store. Each Retail_Item has four attributes: int itemNumber, String description, int numInInventory, and double price.
What I'm trying to figure out is how to read in each line from the file and turn each line into an object. My first thought was to create a while loop with vars like currentItemNumber, currentDescription, etc. So I tried this:
while (file.hasNextLine()) {
currentItemNumber = file.nextInt();
currentDescription = file.next
} // end while
But I got stuck there because every other time I've read in a String to a Scanner, I've always used nextLine. Can't use that here though, because each line contains multiple attributes of the object, not a String within a line. Is there a way to do this in the structure I'm trying to use, or should I be doing this a different way? I know I've seen and done some things where I parsed a String into separate pieces which I've seen people refer to as "tokens." Would people recommend reading each line in and then parsing it into separate tokens, then assigning each token to its appropriate attribute? Then I guess I'd have to cast those tokens into the appropriate object, since I think reading the whole line in and then parsing it would make each piece a String.
Here's a sample of what's in the text file (which can't be changed in any way, per the professor's instructions):
1000 Pants 10 19.99
2000 Jeans 2 25.95
3000 Shirt 12 12.50
Thanks in advance for your sage wisdom if you've got it.
The following code fulfills your requirement as stated in your question, namely how to create an instance of class RetailItem from a line of text from your text file. I presume it uses things that you may not have learned yet, like class Paths and try-with-resources. This is just used to scan through your file.
First, class RetailItem contains the members you described in your question. Next, I wrote a constructor for class RetailItem that creates a new instance and initializes the instance members. Then I wrote a toString() method that displays the contents of a RetailItem object in "human readable" form. Finally a main() method that reads your text file (which I named "clothes.txt"), line by line - using a Scanner. For each line read, the code splits it using a delimiter which consists of at least one whitespace character. (I presume you haven't yet learned about regular expressions in java.) Then I convert the elements of the String array returned by method split() into appropriate data types that are required by the RetailItem constructor. Then I call the constructor, thus creating an instance of class RetailItem (as you requested) and I print the created instance.
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Scanner;
public class RetailItem {
private static final int FIELDS = 4;
private int itemNumber;
private String description;
private int numInInventory;
private double price;
public RetailItem(int itemNumber, String description, int numInInventory, double price) {
this.itemNumber = itemNumber;
this.description = description;
this.numInInventory = numInInventory;
this.price = price;
}
#Override // java.lang.Object
public String toString() {
return String.format("%4d %-5s %2d %2.2f", itemNumber, description, numInInventory, price);
}
public static void main(String[] args) {
try (Scanner file = new Scanner(Paths.get("clothes.txt"))) {
while (file.hasNextLine()) {
String record = file.nextLine();
String[] fields = record.split("\\s+");
if (fields.length == FIELDS) {
int itemNumber = Integer.parseInt(fields[0]);
String description = fields[1];
int numInInventory = Integer.parseInt(fields[2]);
double price = Double.parseDouble(fields[3]);
RetailItem item = new RetailItem(itemNumber, description, numInInventory, price);
System.out.println(item);
}
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
I think the way that I would do is, like you said, parse each line into separate strings and then assign each piece to instance variables of the object you are building.
I have done something like this before, maybe it can be helpful.
Scanner fileScan;
File babyNameFile = new File("yob2015.txt");
try {
fileScan = new Scanner(babyNameFile);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
return;
}
String currentLine;
int numberOfGirlsNames = 0;
while (fileScan.hasNextLine()) {
String[] values;
currentLine = fileScan.nextLine();
values = currentLine.split(",");
if (values[1].equals("F")) {
numberOfGirlsNames = numberOfGirlsNames+1;
}
}
System.out.println("Number of female names was "+numberOfGirlsNames);

How to easily process CSV file to List<MyClass>

In my application I use a lot of CSV files which I have to read and build a lists based on them. I'd like to discover an easy way to do this. Do you know any easy framework which does it without using number of config files etc?
For instance, I have got a class Person:
public class Person {
String name;
String surname;
double shoeSize;
boolean sex; // true: male, false:female
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public double getShoeSize() {
return shoeSize;
}
public void setShoeSize(double shoeSize) {
this.shoeSize = shoeSize;
}
public boolean isSe) {
return sex;
}
public void setSeboolean sex) {
this.sex = sex;
}
}
For this class, I have prepared CSV file:
name,surname,shoesize,sex
Tom,Tommy,32,true
Anna,Anny,27,false
How can I do it easily?
One of the simplest ways to read and serialize data is by using the Jackson library.
It also has an extension for CSV, you can find the wiki here
Let's say you have a Pojo like this:
#JsonPropertyOrder({ "name", "surname", "shoesize", "gender" })
public class Person {
public String name;
public String surname;
public int shoesize;
public String gender;
}
And a CSV like this:
Tom,Tommy,32,m
Anna,Anny,27,f
Then reading it is done like so:
MappingIterator<Person> personIter = new CsvMapper().readerWithTypedSchemaFor(Person.class).readValues(csvFile);
List<Person> people = personIter.readAll();
This is simple enough for my taste, basically all you need to do is add the column order in your CSV file using the #JsonPropertyOrder annotation and then just read the file using the above 2 lines.
There are lot of good frameworks written in Java to parse a CSV file and form a List of Objects. OpenCSV, JSefa & jCSV are to name a few of them.
For your requirement, I believe jCSV suits the best. Below is the sample code from jCSV which you can make use of easily.
Reader reader = new FileReader("persons.csv");
CSVReader<Person> csvPersonReader = ...;
// read all entries at once
List<Person> persons = csvPersonReader.readAll();
// read each entry individually
Iterator<Person> it = csvPersonReader.iterator();
while (it.hasNext()) {
Person p = it.next();
// ...
}
Moreover, parsing a CSV file and converting it to a List isn't a big deal and it can be achieved without using any framework, as shown below.
br = new BufferedReader(new FileReader(csvFileToRead));
List<Person> personList = new ArrayList<>();
while ((line = br.readLine()) != null) {
// split on comma(',')
String[] personCsv = line.split(splitBy);
// create car object to store values
Person personObj = new Person();
// add values from csv to car object
personObj.setName(personCsv[0]);
personObj.setSurname(personCsv[1]);
personObj.setShoeSize(personCsv[2]);
personObj.setGender(personCsv[3]);
// adding car objects to a list
personList.add(personObj);
}
If the mapping of CSV columns to bean object is complex, repetitive or large in real case scenario, then it can be done easily by using DozerBeanMapper.
Hope this will help you.
Shishir
Not sure if you need to go as far as using an external library (and taking the usually implied performance hit). It's a pretty simple thing to implement. And if nothing else, it always helps to know what's going on behind the scenes in such a library:
public List<Person> readFile(String fileName) throws IOException {
List<Person> result = new ArrayList<Person>();
BufferedReader br = new BufferedReader(new FileReader(new File(fileName)));
try {
// Read first line
String line = br.readLine();
// Make sure file has correct headers
if (line==null) throw new IllegalArgumentException("File is empty");
if (!line.equals("name,surname,shoesize,sex"))
throw new IllegalArgumentException("File has wrong columns: "+line);
// Run through following lines
while ((line = br.readLine()) != null) {
// Break line into entries using comma
String[] items = line.split(",");
try {
// If there are too many entries, throw a dummy exception, if
// there are too few, the same exception will be thrown later
if (items.length>4) throw new ArrayIndexOutOfBoundsException();
// Convert data to person record
Person person = new Person();
person.setName ( items[0] );
person.setSurname ( items[1] );
person.setShoeSize(Double .parseDouble (items[2]));
person.setSex (Boolean.parseBoolean(items[3]));
result.add(person);
} catch (ArrayIndexOutOfBoundsException|NumberFormatException|NullPointerException e) {
// Caught errors indicate a problem with data format -> Print warning and continue
System.out.println("Invalid line: "+ line);
}
}
return result;
} finally {
br.close();
}
}
Note that the catch statement uses Java 7 multi-catch. For older Java versions, either split it into 3 catch blocks or replace ArrayIndexOutOfBoundsException|NumberFormatException|NullPointerException with Exception. The latter is usually discouraged as it masks and ignores all other exceptions as well, but in a simple example like this, the risk is probably not too high.
This answer, unfortunately, is specific to your problem, but given that it is very straight forward, it should be easy to adapt to other situations as well...
Another neat thing you can do is to match line inside the while loop with a regular expression rather than simply splitting it based on a comma. That way you could also implement data validation in one shot (for example only match a sensible number for shoe size).
Note that the above implementation doesn't work if you have names that contain commas which are then enclosed in quotes (like "Jackson, Jr." as a last name). You can cover this case "easily" if you use regular expressions as described above, or by checking the first letter of the last name and if it is a quotation mark, combine item[1] with item[2] and use item[3] and item[4] instead for the shoesize and sex. This special case will likely be covered by most of the external libraries suggested here, so if you're not worried about any dependencies, licensing issues, and performance hits, those might be the easier way out...
opencsv is a good and simple solution. It is a small but powerful library. You can download it from the opencsv website (direct download from sourceforge, use the jar in the deploy directory) or use maven.
The java bean mapping feature makes it really simple because your CSV column names are matching the property names of your class (it ignores the different capitalisation).
How to use it:
Reader reader = // ... reader for the input file
// let it map the csv column headers to properties
CsvToBean<Person> csvPersons = new CsvToBean<Person>();
HeaderColumnNameMappingStrategy<Person> strategy = new HeaderColumnNameMappingStrategy<Person>();
strategy.setType(Person.class);
// parse the file and get a list of persons
List<Person> persons = csvPersons.parse(strategy, reader);
That's all.
I solved this recently by using Immutables and Jackson, and I think it's a great way to go if you're willing to use these libraries.
Immutables and Jackson integrate very well. To take OP's example, all you'd have to do is specify the Immutables class like so (annotations qualified for snippet explicitness):
#org.immutables.value.Value.Immutable
#com.fasterxml.jackson.databind.annotation.JsonDeserialize(as = ImmutablePerson.class)
public interface Person {
String getName();
String getSurname();
double getShoeSize();
boolean getSex();
}
Then, using the Jackson CSV module, you can easily deserialize each row of the CSV into the class Immutables has generated for you:
List<Person> loadPeople(File personsCsvFile) throws IOException {
CsvSchema schema = CsvSchema.emptySchema().withHeader();
MappingIterator<Person> personsIterator = new CsvMapper()
.readerFor(Person.class)
.with(schema)
.readValues(personsCsvFile);
return personsIterator.readAll();
}
Use OpenCSV
Here is a complete example that reads entries and adds them to a List:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
public class CSVReaderImplementor {
private String fileName;
private CSVReader reader;
private List<String[]> entries;
public CSVReaderImplementor(String fileName) throws IOException, FileNotFoundException {
this.fileName = fileName;
reader = new CSVReader(new FileReader(this.fileName));
entries = reader.readAll();
}
public List getEntries() {
return entries;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
CSVReaderImplementor cri = new CSVReaderImplementor("yourfile.csv");
for(int i = 0; i < 50; i++) {
System.out.println(cri.getEntries().get(i).toString());
}
}
}
A List of type String[] is returned. You can iterate through the String array for each entry in the list and use the values at each index to populate your Bean constructor.
I think SuperCSV + Dozer easy to use and quite robust for java bean CSV serialization
http://supercsv.sourceforge.net/dozer.html

Java Inventory - ADT class & File Input troubles

I've hit a roadblock with this program.
I have a program that involves creating a program that involves the "inventory" of Cadillac, and among all else, I cannot find answers to my questions.
I just do not know what to do. I'll provide the directions and then post the syntax I have so far.
Here is what I have to do:
inventory for a fictional Cadillac Dealership and allows the inventory to be searched to display a list of cars that meet specific criteria.
create an ADT class called Cadillac which contains four fields of instance data: Strings for model name, stock number and color, and an integer for price. The class contains one Constructor, which receives values for all four instance fields, and assigns the parameter values to the instance variables. The class also contains a simple accessor method and mutator method for each field of instance data.
When the program is ran, it loads the inventory from a file, "inventory.dat".
Here is a sample of the contents of the file:
DTS 11210 Glacier White 42706
Escalade 66502 Crimson Pearl 65547
XLR 58362 Radiant Bronze 78840
SRX 16218 Radiant Bronze 44522
Each line (each record) contains 4 fields of data: strings for model name, a 5–digit stock number, and color, and an integer for price. The delimiter between the fields is a tab character (“\t”).
In main(), create an array of Cadillac objects, read in a record from the file, split it into its 4 fields, create a Cadillac object and add it to the array.
the inventory file changes and your program needs to work no matter how many records are in the file. You are guaranteed there will never be more than 100 records in the file (they only have room for 100 cars on the lot), and that each record will contain exactly 4 fields of valid data.
The user can search the inventory two ways: by model name and by price. After you load the inventory, ask the user which search they want to do. If they indicate “by model name”, have them enter the name to search for. The valid model names are: DTS, Escalade, ESV, EXT, SRX, STS, and XLR. Search the inventory for all cars with that name and display a table of results on the console screen.
-When the user indicates he/she wants to search by price, have them enter the price to search
for, then perform the search, displaying all cars that have a price within $3,000 of the search
price.
- The program should loop to do as many searches as the user wants. Let the user end the
program by clicking a “Cancel” button when asked for the type of search they want to perform.
A “Cancel” button on the second question (the model or price to search for) should not end the
program, but your code should recognize it as an invalid entry, and not throw an exception.
Besides the list output, all input and output in the program should be with JOptionPane dialogs.
Here is what I have so far:
import java.util.Scanner;
import java.io.*;
public class Inventory {
public static void main ( String[] args )
{
String line;
String[] fields;
String[] items;
int count = 0;
int recCount;
Cadillac[] list = new Cadillac[100];
try
{
BufferedReader br = new BufferedReader( new FileReader( "inventory.dat" ) );
line = br.readLine();
while( line != null )
{
fields = line.split( "\t" );
items[count++] = new Cadillac( fields[0], fields[1], fields[2],
fields[3] );
line = br.readLine();
}
br.close();
}
catch( IOException e )
{
System.out.println( "Can't open input file. Program terminating." );
System.exit( 1 );
}
}
public static int loadArray(Cadillac[] items)
{
}
}
class Cadillac {
//Instance data
private String model;
private String stockNum;
private String color;
private int price;
//Constructor
public Cadillac(String mdl, String stckNum, String clr, int prc)
{
model = mdl;
stockNum = stckNum;
color = clr;
price = prc;
}
//Set of Accessor and Mutator Methods
public String getModel(){
return model;
}
public void setModel(String newModel){
model = newModel;
}
public String getStockNum(){
return stockNum;
}
public void setStockNum(String newStockNum){
stockNum = newStockNum;
}
public String getColor(){
return color;
}
public void setColor(String newColor){
color = newColor;
}
public int getPrice(){
return price;
}
public void setPrice(int newPrice){
price = newPrice;
}
}
PLEASE HELP! I do not have any other idea of what to do.
In regards to your comment:
It is saying that it cannot find the symbol constructor Cadillac
Your only constructor defined for Cadillac has parameters (String, String, String, int) but when you try to instantiate the object in main, you pass it four Strings. Java is throwing an error because it can't find the correct constructor.
Either pass the last parameter as an int or create a new constructor for your arguments.
Your most immediate problem is that the signature of your data objects constructor is incompatible with the way you are calling it. You have declared your constructor as so:
public Cadillac(String mdl, String stckNum, String clr, int prc)
It takes three string arguments and an int, but you are calling it with four strings:
new Cadillac( fields[0], fields[1], fields[2], fields[3] );
Thats the source of the compile error you reported seeing. You should convert your last String to an int.
new Cadillac( fields[0], fields[1], fields[2], Integer.parseInt(fields[3]).intValue() );
Apart from that there is another glaring error in your code. You declare an array of strings, but are attempting to store instances of 'Cadillac' into it:
String[] items;
// ...
items[count++] = new Cadillac( ... );
I won't code your entire homework for you, but my advise would be to first right down in plain English sentences, each task that needs to be accomplished in order to complete the overall program. Then start translating each individual sentence into code, ideally in the form of methods on your classes that can be called. As you run into issues, come back and ask specific questions and I'm sure there will be someone here willing to help you more.
Good luck.

Categories