Why is useDelimiter not working java - java

So I my program reads a .txt file and I am using .useDelimeter to seperate the pets and put them in an arraylist:
try{
Scanner petReader = new Scanner(new File("pet3-dogs.txt"));
petReader.useDelimiter(",");
String line2 = petReader.nextLine();
while(petReader.hasNextLine()){ //the while loop stores each attribute in the appropriate variable and arraylist of petshops while there's another line.
petReader.useDelimiter(",");
String shop =petReader.next();
String type =petReader.next();
double price = Double.parseDouble(petReader.next());
Date date = df.parse(petReader.next());
String notes =petReader.nextLine();
String size =petReader.nextLine();
String neutered =petReader.nextLine();
petReader.useDelimiter(",");
pets.add(new Pet(shop, type, price, date, notes, size, neutered));
System.out.println(pets.toString());
}
} catch(Exception e){
JOptionPane.showMessageDialog(null, e); //if the program wasn't able to read the file, it will display a message dialog.
}
This is the output. Infact it gets the next petshops in the last two variables:
[Solly's Pet Store
Giant Schnauzer
£176.43
Wed Jul 07 00:00:00 BST 2010
,none,Medium,no
The Menagerie,Neapolitan Mastiff,293.73,29/08/2010,none,Medium,no
Obsborne Road Pet Store,Basenji,224.27,13/10/2010,none,Large,yes
]
My expected output is
Solly's Pet Store
Giant Schnauzer
£176.43
Wed Jul 07 00:00:00 BST 2010
none
Medium
no.
This is my Pet class:
public class Pet {
private String shop;
private String type;
private double price;
private Date dateAquired;
private String notes;
private String size;
private String neutered;
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getNeutered() {
return neutered;
}
public void setNeutered(String neutered) {
this.neutered = neutered;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getShop() {
return shop;
}
public void setShop(String shop) {
this.shop = shop;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getDateAquired() {
return dateAquired;
}
public void setDateAquired(Date dateAquired) {
this.dateAquired = dateAquired;
}
public Pet(String pShop, double pPrice){
this.shop = pShop;
this.price = pPrice;
}
public Pet(String pShop, String pType, double pPrice, Date pDateAcquired, String pNotes, String pSize, String pNeutered){
this.shop = pShop;
this.type = pType;
this.price = pPrice;
this.dateAquired = pDateAcquired;
this.notes = pNotes;
this.size = pSize;
this.neutered = pNeutered;
}
#Override
public String toString(){
return getShop()+"\n"
+getType()+"\n"
+"£"+getPrice()+"\n"
+getDateAquired()+"\n"
+getNotes()+"\n"
+getSize()+"\n"
+getNeutered()+"\n";
}
}
This is the file it is reading from.

When you do:
String notes =petReader.nextLine();
It reads the whole line until it encounters \n, which contains the String:
,none,Medium,no
The rest of the line has been already read.
Then, in the next two lines, you again use nextLine(), and so, it again reads complete lines, and hence you get that output.
You must use:
String notes =petReader.next();
String size =petReader.next();
String neutered =petReader.next();

Related

Java: Arraylist out of bounds when processing file [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am trying to create an ArrayList that reads a .csv file, processes the data into an ArrayList, and then print the list out.
My code so far.
The BankRecords class
import java.io.*;
import java.util.*;
public class BankRecords
{
String sex, region, married, save_act, current_act, mortgage, pep;
int children;
double income;
private String id;
private int age;
public BankRecords(String gender, String area, String marriage, String SaveAccount, String CurrentAccount, String HouseBill, String pepp, int minors, double paycheck, String identification, int years)
{
this.sex = gender;
this.region = area;
this.married = marriage;
this.save_act = SaveAccount;
this.current_act = CurrentAccount;
this.mortgage = HouseBill;
this.pep = pepp;
this.children = minors;
this.income = paycheck;
this.id = identification;
this.age = years;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
public String getRegion()
{
return region;
}
public void setRegion(String region)
{
this.region = region;
}
public String getMarried()
{
return married;
}
public void setMarried(String married)
{
this.married = married;
}
public String getSave_act()
{
return save_act;
}
public void setSave_act(String save_act)
{
this.save_act = save_act;
}
public String getCurrent_act()
{
return current_act;
}
public void setCurrent_act(String current_act)
{
this.current_act = current_act;
}
public String getMortgage()
{
return mortgage;
}
public void setMortgage(String mortgage)
{
this.mortgage = mortgage;
}
public String getPep()
{
return pep;
}
public void setPep(String pep)
{
this.pep = pep;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public int getChildren()
{
return children;
}
public void setChildren(int children)
{
this.children = children;
}
public double getIncome()
{
return income;
}
public void setIncome(double income)
{
this.income = income;
}
}
The Client abstract class
import java.io.*;
import java.util.*;
public abstract class Client
{
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
static BankRecords robjs[] = new BankRecords[600];
public static void readData()
{
try
{
BufferedReader br;
String filepath = "C:\\Users\\eclipse-workspace\\Bank_Account\\src\\bank-Detail.csv";
br = new BufferedReader(new FileReader (new File(filepath)));
String line;
while ((line = br.readLine()) != null)
{
BankArray.add(Arrays.asList(line.split(",")));
}
}
catch (Exception e)
{
e.printStackTrace();
}
processData();
}
public static void processData()
{
int idx=0;
for (List<String> rowData: BankArray)
{
robjs[idx] = new BankRecords(null, null, null, null, null, null, null, idx, idx, null, idx);
robjs[idx].setId(rowData.get(0));
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
idx++;
}
printData();
}
public static void printData()
{
System.out.println("ID\tAGE\tSEX\tREGION\tINCOME\tMORTGAGE");
int final_record = 24;
for (int i = 0; i < final_record; i++)
{
System.out.println(BankArray.get(i) + "\t ");
}
}
}
The BankRecordsTest class (extends Client)
import java.util.*;
import java.io.*;
public class BankRecordsTest extends Client
{
public static void main(String args [])
{
readData();
}
}
The error
And here is the error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at java.util.Arrays$ArrayList.get(Unknown Source)
at Client.processData(Client.java:33)
at Client.readData(Client.java:24)
at BankRecordsTest.main(BankRecordsTest.java:7)
I'm not sure what the index problem is. Do note that if you run the ReadData() and PrintData() functions separately, the code runs fine but the ProcessData() method causes issues.
I think your data is likely not clean and you are making assumptions about the length of your array. The error you are getting stems from this line:
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
Clearly, rowData doesn't have 2 items (or more). This is why you are getting ArrayIndexOutOfBoundsException. So you want to check where your variable was initialized. You quickly realize it comes from
for (List<String> rowData: BankArray)
So then, the following question is where BankArray gets initialized. That happens in 2 places. First of all
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
You are creating an empty list. So far so good. Note that you don't need to (and therefore shouldn't) initialize with a size. Lists are not like arrays insofar as they can easily grow and you don't need to give their size upfront.
The second place is
BankArray.add(Arrays.asList(line.split(",")));
This is likely where the issue comes from. Your row variable contains the results of Arrays.asList(line.split(",")). So the size of that list depends on the number of commas in that string you are reading. If you don't have any commas, then the size will be 1 (the value of the string itself). And that's what leads me to concluding you have a data quality issue.
What you should really do is add a check in your for (List<String> rowData: BankArray) loop. If for instance, you expect 2 fields, you could write something along the lines of:
if (rowData.size()<2){
throw new Exception("hmmm there's been a kerfuffle');
}
HTH

How can I create a instance of a class with an array of Strings as the only instance variable?

I have written a class Form. An array of 10 Strings is the only parameter in the constructor. How can I create an instance of the class? I'm sure there are other problems in my setters and getters but I cant test them until I fix this.
public class FormLab {
public static void main(String[]args){
Form f1 = new Form(String webForm);
System.out.println(print(String[] webForm));
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}
}
public class Form {
String[] webForm = new String[10];
private String userID;
private String pw;
private String pw2;
private String email;
private String name;
private String address;
private String city;
private String state;
private String zip;
private String telephone;
//constructor
public Form(String[] webForm){
//filling array with field values
webForm[0] = "0123456789";
webForm[1] = "java123";
webForm[2] = "java123";
webForm[3] = "luke.skywalker#jedi.com";
webForm[4] = "Luke Skywalker";
webForm[5] = "1234 The Force Way";
webForm[6] = "Rome";
webForm[7] = "GA";
webForm[8] = "30161";
webForm[9] = "7065551234";
}
public boolean getEmptyFields() {
//boolean empty = false;
for(int i = 0; i < webForm.length; i++){
if(webForm[i]!= null){
return true;
}
}
return false;
}
public String getUserID(){
return userID;
}
public void setUserId(String userID){
this.userID = userID;
}
public String getPw(){
return pw;
}
public void setPw(String pw){
this.pw = pw;
}
public String getPw2(){
return pw2;
}
public void setPw2(String pw2){
this.pw2 = pw2;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public String getCity(){
return city;
}
public void setCity(String city){
this.city = city;
}
public String getState(){
return state;
}
public void setState(String state){
this.state = state;
}
public String getZip(){
return userID;
}
public void setZip(String zip){
this.zip = zip;
}
public String getTelephone(){
return telephone;
}
public void setTelephone(String telephone){
this.telephone = telephone;
}
public int getCharNum(String userID) {
int userLength = 0;
//userID.length();
return userLength;
}
public boolean getPwCheck() {
boolean check = pw.equalsIgnoreCase(pw2);
// pw.equalsIgnoreCase(pw2);
return check;
}
public boolean getEmailCheck(String email) {
if(email.contains("#") && email.contains(".")){
return true;
}
return false;
}
public static void getPrint(String[] webForm) {
System.out.println(webForm.toString());
}
}
Use method arraycopy.
public Form(String[] webForm){
System.arraycopy(webForm, 0, this.webForm, 0, webForm.length);
}
The constructor takes a string array as argument, but you are passing it a string, try:
myList = new String[];
myForm = new Form(myList);
You need to declare your array before putting it as a parameter as follow:
public class FormLab {
public static void main(String[]args){
String webForm = new String[10];
Form f1 = new Form(webForm);
/*System.out.println(print(String[] webForm)); THIS IS WRONG*/
/*TO PRINT THE VALUES IN THE ARRAY YOU NEED TO WRITE A METHOD IN UR
FORM CLASS THAT WILL LOOP THRU UR VARIABLE AND PRINT*/
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}

How to convert multiple string into arraylist?

I m new in android.I want to add these String variables to ArrayList, what I am doing now.
Suppose I have a four of String Variables.....
String number = "9876543211";
String type = "incoming";
String date = "1/1/2016";
String duration = "45 sec";
Here is my java code.......
while (managedCursor.moveToNext()) {
String number = managedCursor.getString(number1);
String type2 = managedCursor.getString(type1);
String date = managedCursor.getString(managedCursor.getColumnIndexOrThrow("date")).toString();
java.util.Date date1 = new java.util.Date(Long.valueOf(date));
String duration = managedCursor.getString(duration1);
String type = null;
String fDate = date1.toString();
int callcode = Integer.parseInt(type2);
sb.append("\nPhone Number:--- " + number + "");
sb.append(" \nCall Type:--- " + type + " ");
sb.append("\nCall Date:--- " + fDate + "");
sb.append("\nCall duration in sec :--- " + duration);
sb.append("\n----------------------------------");
}
As 4castle suggest, you should really have a custom class - which looking at the properties you are interested in, you might want to name "CallLogEntry" and then have properties for this class. Here is an example of such a custom class.
public class CallLogEntry {
String number;
String type;
String date;
String duration; //this should ideally be of type Long (milliseconds)
public CallLogEntry(){
//do stuff if necessary for no-params constructor
}
public CallLogEntry(String number, String type, String date, String duration){
this.number = number;
this.type = type;
this.date = date;
this.duration = duration;
}
//getters and setters go here..
getNumber(){ return this.number;}
setNumber(String number){ this.number = number;}
//...the rest of them...
}
Than it makes more sense to have an ArrayList of CallHistoryEntry items like this:
//...declare list of call-log-entries:
List<CallLogEntry> callLogEntryList = new ArrayList<CallLogEntry>();
//...add entries
CallLogEntry entry = new CallLogEntry(number, type, date, duration);
callLogEntryList.add(entry);
The advantage of doing it like this, especially in an Android app, is that later you may pass this list to some list-adapter for a list-view.
I hope this helps.
Create JavaBean Class as follows
public class DataBean {
String number;
String type;
String date;
String duration;
public DataBean(String number, String type, String date, String duration) {
this.number = number;
this.type = type;
this.date = date;
this.duration = duration;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
Now create Arryalist as follows
ArrayList<DataBean> dataBeanList = new ArrayList<>();
DataBean dataBean=new DataBean(number,type,date,duration);
dataBeanList.add(dataBean);//added bean object arrylist
For Retrieving data do as follow
// iterate through arraylist as follows
for(DataBeand d: dataBeanList ){
if(d.getName() != null && d.getDate()!=null)
//something here
}

Adding Items to my inventory in Java

I am making a text-based game on JavaFX, and after I hit a tree, I want to get Oak logs.
I have already built my inventory, and I have put default items in it such as Water, Bread, etc.
I am trying to add my Oak Logs to my inventory, but nothing is working.
Here is a part of my code:
Item ItemList[] = {new Bread(), new OakLog()};
Optional<ButtonType> result = alert.showAndWait();
if(result.get() == buttonTypeOak) {
woodcuttingXP = woodcuttingXP + oakXP;
dialogue.appendText("You swing at an Oak tree. + " + oakXP + "XP.\n");
dialogue.appendText("You gathered 1 log.\n");
mainCharacter.getInventory().add(new OakLog());
}
Here is my Item Class:
package game;
public class Item {
private String name;
private int weight;
private int quantity;
private int value;
private String description;
public Item(String name, int value, String description) {
this.name = name;
this.value = value;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
return getName();
}
}
And finally, here is my Character class:
package game;
import java.util.ArrayList;
import beverages.Water;
import items.OakLog;
import rawFood.Bread;
public class Character {
private String name;
private int hydrationLevel;
private int healthLevel;
private int hungerLevel;
private int woodcuttingLevel;
public int getWoodcuttingLevel() {
return woodcuttingLevel;
}
public void setWoodcuttingLevel(int woodcuttingLevel) {
this.woodcuttingLevel = woodcuttingLevel;
}
public int getHungerLevel() {
return hungerLevel;
}
public void setHungerLevel(int hungerLevel) {
this.hungerLevel = hungerLevel;
}
private ArrayList<Item> inventory = new ArrayList<Item>();
public ArrayList<Item> getInventory() {
return inventory;
}
public void setInventory(ArrayList<Item> inventory) {
this.inventory = inventory;
}
//creates a person with two basic items
public Character(String name){
this.name = name;
this.hydrationLevel = 100;
this.healthLevel = 100;
this.hungerLevel = 100;
this.woodcuttingLevel = 1;
addToInventory (new Bread());
addToInventory (new OakLog());
addToInventory (new Water());
}
//GETTERS AND SETTERS
public String getName() {
return name;
}
public int getHydrationLevel() {
return hydrationLevel;
}
public void setHydrationLevel(int hydrationLevel) {
this.hydrationLevel = hydrationLevel;
}
public int getHealthLevel() {
return healthLevel;
}
public void setHealthLevel(int healthLevel) {
this.healthLevel = healthLevel;
}
//END GETTERS AND SETTERS
/*Method Name: eat()
*Method Inputs: a piece of food
*Method Purpose: Will allow the user to eat food
*/
public Item getItemFromInventory(int index){
Item item = inventory.get(index);
return item;
}
public void addToInventory(Item item){
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
else{
item.setQuantity(1);
inventory.add(item);
}
}
public String toString(){
return "Character Stats:\nName:" + getName() + "\nHydration: " + getHydrationLevel() + "\nHealth: " + getHealthLevel() + "\nWoodcutting: " + getWoodcuttingLevel();
}
}
In your code, you have:
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
This just updates the quantity of the local variable item in the method, not the item in the inventory.

Homework Help; Reading from multiple files into Vectors/Arrays

Okay my assignment is to read in from 2 separate files. The first file reads in "HallOfFameMember" and should then be stored in a vector.
The second should read in and then be stored to an array of HallOfFame
The HallOfFameMember object has 10 fields. In order firstName, lastName, deceased, month born, day born, year born, totalEarned, yearsPlayed, yearInducted, hall of fame id
The day/month/year born are all going to a separate class to create a date born. The date born is then set within HallOfFameMember. The Fields for a record will be separated by varying numbers of spaces and/or tabs (whitespaces).
After reading a record from this file, call the 10-arg constructor of HallOfFameMember, using the fields from the record as arguments in the constructor call. Add this new HallOfFameMember object to tempHallOfFameMemberVec.
The HallOfFame object has 5 fields. In order hallOfFameId, city, costToVisit, numberOfVisitorsPerYear, and name.
After reading a record from this file, call the 5-arg constructor of class HallOfFame, using the arguments obtained from the line in the file. Add this new HallOfFame object to tempHallOfFameArr.
This is all to be done from the command line.
I know that my current code will not work, I was just trying to figure out some way to do this. Vectors are completely new to me, along with BufferedReader, and I've been trying to use the examples on javapractice.com as well as a few other sites for reference. I know it will be something small that I am overlooking/missing and Ill have a duh moment when I figure it out.
At any rate my current question is this.
How do I read in from a file that has "any number of white spaces/tabs" as the delimiter. And then parse that into the appropriate fields within the appropriate class?
Giving me the code isn't gonna help, if you could just point me to a website or link that I can read to have my duh moment that would be great.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Vector;
public class HW4 {
/**
* #param args
*/
public static void main(String[] args) {
FileReader inputFileA = new FileReader("");
FileReader inputFileB = new FileReader("");
BufferedReader inputB = new BufferedReader(inputFileB);
Vector<HallOfFameMember> tempHallOfFameMemberVec = new Vector<HallOfFameMember>();
try{
BufferedReader inputA = new BufferedReader(inputFileA);
try {
String line = null;
while ((line = inputA.readLine()) != null){
}
}
}
String newHallOfFameLine = inputB.toString();
String delims = "[ \t]";
HallOfFame[] tempHallOfFameArr = newHallOfFameLine.split(delims);
for (int i = 0; i < args.length; i += 5) {
tempHallOfFameArr[i/5].setHallOfFameId(Integer.parseInt(args[i]));
tempHallOfFameArr[i/5].setCity(args[i+1]);
tempHallOfFameArr[i/5].setCostToVisit(Integer.parseInt(args[i+2]));
tempHallOfFameArr[i/5].setNumberOfVisitorsPerYear(Integer.parseInt(args[i+3]));
tempHallOfFameArr[i/5].setName(args[i+4]);
}
}
class HallOfFameMember {
private String firstName;
private String lastName;
private boolean deceased;
private int dateOfBirth;
private double totalEarned;
private int yearsPlayed;
private int yearInducted;
private int HallOfFameId;
public HallOfFameMember() {
}
public HallOfFameMember(String firstName, String lastName,
boolean deceased, int day, int month, int year, double totalEarned,
int yearsPlayed, int yearInducted, int hallOfFameId) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.deceased = deceased;
this.dateOfBirth = month + day + year;
this.totalEarned = totalEarned;
this.yearsPlayed = yearsPlayed;
this.yearInducted = yearInducted;
HallOfFameId = hallOfFameId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isDeceased() {
return deceased;
}
public void setDeceased(boolean deceased) {
this.deceased = deceased;
}
public int getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(int dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public double getTotalEarned() {
return totalEarned;
}
public void setTotalEarned(double totalEarned) {
this.totalEarned = totalEarned;
}
public int getYearsPlayed() {
return yearsPlayed;
}
public void setYearsPlayed(int yearsPlayed) {
this.yearsPlayed = yearsPlayed;
}
public int getYearInducted() {
return yearInducted;
}
public void setYearInducted(int yearInducted) {
this.yearInducted = yearInducted;
}
public int getHallOfFameId() {
return HallOfFameId;
}
public void setHallOfFameId(int hallOfFameId) {
HallOfFameId = hallOfFameId;
}
public double averageYearlySalary(double averageYearlySalary) {
return averageYearlySalary = (totalEarned / yearsPlayed);
}
}
class Date {
private int month;
private int day;
private int year;
public Date(int month, int day, int year) {
super();
this.month = month;
this.day = day;
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
class HallOfFame {
private int hallOfFameId;// ID of the hall of fame
private String name;// Name of the hall of fame
private String city;// the city in which the hall of fame is located
private double costToVisit;// cost in dollars for a visitor to a hall of
// fame for 1 day
private int numberOfVisitorsPerYear;
private static final double maxCostToVisit = 37.50;
public HallOfFame() {
}
public HallOfFame(int hallOfFameId, String name, String city,
double costToVisit, int numberOfVisitorsPerYear) {
super();
this.hallOfFameId = hallOfFameId;
this.name = name;
this.city = city;
this.costToVisit = costToVisit;
this.numberOfVisitorsPerYear = numberOfVisitorsPerYear;
}
public int getHallOfFameId() {
return hallOfFameId;
}
public void setHallOfFameId(int hallOfFameId) {
this.hallOfFameId = hallOfFameId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public double getCostToVisit() {
if (costToVisit <= maxCostToVisit) {
return costToVisit;
} else
return maxCostToVisit;
}
public void setCostToVisit(double costToVisit) {
this.costToVisit = costToVisit;
}
public int getNumberOfVisitorsPerYear() {
return numberOfVisitorsPerYear;
}
public void setNumberOfVisitorsPerYear(int numberOfVisitorsPerYear) {
this.numberOfVisitorsPerYear = numberOfVisitorsPerYear;
}
public static double getMaxcosttovisit() {
return maxCostToVisit;
}
public double totalAnnualRevenue(double totalAnnualRevenue) {
totalAnnualRevenue += costToVisit * numberOfVisitorsPerYear;
return totalAnnualRevenue;
}
}
class ReportWriter{
private Vector<HallOfFameMember> hallOfFameMemberVec;
private HallOfFame[] hallOfFameArr;
public ReportWriter() {
}
public Vector<HallOfFameMember> getHallOfFameMemberVec() {
return hallOfFameMemberVec;
}
public void setHallOfFameMemberVec(Vector<HallOfFameMember> hallOfFameMemberVec) {
this.hallOfFameMemberVec = hallOfFameMemberVec;
}
public HallOfFame[] getHallOfFameArr() {
return hallOfFameArr;
}
public void setHallOfFameArr(HallOfFame[] hallOfFameArr) {
this.hallOfFameArr = hallOfFameArr;
}
public void displayReports(){
}
}
A couple tips:
I don't want to do your homework for you, but I can't think of a quick tutorial to point you to that covers exactly what you're doing.
You're on the right track with .split, but your delimiter expression won't work for multiple spaces/tabs. Try this:
String delims = "\\s+";
That will break up your string on any consecutive sequence of one or more whitespace characters.
Also, you need to move the split up into your while loop, as well as the creation of each HallOfFameMember object. In each iteration of the loop you want to:
Split the line that you read from the file to create an array of strings representing the values for one record.
Create a new HallOfFameMember using the values from your string array. (tempHallOfFameArr[0] for first name, tempHallOfFameArr[1] for last name, etc.)
Add the new HallOfFameMember that you created to your vector
If you'd like more detail on any of these steps, I'm happy to elaborate.

Categories