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.
Related
I am this close to finally completing this assignment, but I've hit a roadblock. For some reason I can't get call aspects of the class in my methods. Does anyone have a way of doing this that works? I've put comments next to the three parts I'm referring to. I do not know what is causing these errors, and Im grateful for any help.
public class Main
{
public static int w = -1;
public static int x = 0;
public static int y = 0;
public static int z = 0;
public static String[] names;
public static int[] years;
public static String[] studios;
public static class Movie{
// instance variables
private int year;
private String title;
private String studio;
private int placement;
// Constructor for objects of class Movie
Movie(String title, int year, String studio)
{
// initialize instance variables
this.title = title;
this.year = year;
this.studio = studio;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public void setPlacement() {
w+=1;
this.placement = w;
}
public int getPlacement() {
return placement;
}
public String getStudio()
{
return studio;
}
public void setStudio(String studio)
{
this.studio = studio;
}
public int getYear()
{
return year;
}
public void setYear(int year)
{
this.year = year;
}
public String toString()
{
String str = String.format("%-30s %4d %-20s", title, year, studio);
return str;
}
}
public static void arrNames(String name) {
x+=1;
names = new String[x];
names[(x-1)] = name.getTitle(); //error here, why can't I just use getTitle()?
}
public static void arrYear(String name) {
y+=1;
years = new int[y];
years[(y-1)] = name.getYear(); //same error
}
public static void arrStudio(String name) {
z+=1;
studios = new String[z];
studios[z-1] = name.getStudio(); //same error
}
public static void setGroup(String name) {
arrNames(name);
arrYear(name);
arrStudio(name);
}
public static void getGroups(String name) {
int a = x;
int b = y;
int c = z;
int d = 0;
int e = 0;
int f = 0;
System.out.println("Names Category: ");
while (a > 0) {
System.out.print(names[d] + " ");
d+=1;
a-=1;
}
System.out.println("Years Category: ");
while (b > 0) {
System.out.print(years[e] + " ");
e+=1;
b-=1;
}
System.out.println("Studios Category: ");
while (c > 0) {
System.out.print(studios[f] + " ");
f+=1;
c-=1;
}
public static void main(String[] args) {
Movie nemo = new Movie("Finding Nemo",2003,"Pixar");
setGroup(nemo.getTitle());
}
}
I will take this exemple:
public static void arrYear(String name) {
y+=1;
years = new int[y];
years[(y-1)] = name.getYear(); //same error
}
You are trying to use the method getYear on the variable name and the name is a String and not a Movie Object
You could just replace the argument from String to Movie like that:
public static void arrYear(Movie name) {
y+=1;
years = new int[y];
years[(y-1)] = name.getYear(); //same error
}
and it should work for all your functions
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
I am trying to use a Scanner object to take in user input that will then be attributed to the following values for an object called TargetHeartRateCalculator.
TargetHeartRateCalculator takes constructor parameters of..
String fName, String lName, int month, int day, int year.
Normally without using the Scanner I would just instantiate the object with the parameters manually like...
TargetHeartRateCalculator patient1 = new TargetHeartRateCalculator("Tom", "Willickers", 01, 25, 1966);
I need to use the Scanner to take user input and then from the user recived input assign values to fName, lName, month, day, year.
I have tried making the object instantiation part of the assignment of the user input through the Scanner object by the syntax is not correct and I'm not even really sure if that's how your supposed to do something like this.
I feel like this is probably a simple solution but the answer is quite evasive to me.
Here is my Driver Class...
import java.util.Scanner;
public class DriverClass {
//--------------------------------------------------------------------------------------
// TARGET HEART RATE CALCULATOR CLASS FUNCTIONALITY TEST
//--------------------------------------------------------------------------------------
TargetHeartRateCalculator patient1 = new TargetHeartRateCalculator("Tom", "Willickers", 01, 25, 1966);
TargetHeartRateCalculator patient2 = new TargetHeartRateCalculator("Bill", "Skarsgard", 8,9, 1990);
//Write a java app that prompts for the persons information
//instantiates an object and prints the information from that object
//first name, last name, date of birth,
// calculates maximum heart rate, and target heart rate.
//and then displays them to the them.
Scanner input = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fnInput = input.nextDouble();
System.out.printf("%nThank you %s %s. Your date of birth is %n" +
"%d and you are %d years old!%n" +
"Your maximum heart rate is %.2f and your %n" +
"Target Heart Rate range is %.2f%n%n" get,
patientInfo(patient1);
patientInfo(patient2);
displayAgeYears(patient1);
displayAgeYears(patient2);
displayMaxHeartRate(patient1);
displayMaxHeartRate(patient2);
displayTargetHeartRate(patient1);
displayTargetHeartRate(patient2);
}
}
Here is my Class
import java.time.LocalDateTime;
public class TargetHeartRateCalculator {
private String fName;
private String lName;
private int dOB;
private int bMonth;
private int bDay;
private int bYear;
private int ageYears;
private double maxHeartRate;
private double lowTargetHearRate;
private double highTargetHearRate;
LocalDateTime now = LocalDateTime.now();
int cYear = now.getYear();
int cMonth = now.getMonthValue();
int cDay = now.getDayOfMonth();
//constructor
public TargetHeartRateCalculator(String fNameIn, String lNameIn, int monthIn, int dayIn, int yearIn) {
fName = fNameIn;
lName = lNameIn;
bMonth = monthIn;
bDay = dayIn;
bYear = yearIn;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public int getBMonth() {
return bMonth;
}
public void setBMonth(int month) {
this.bMonth = month;
}
public int getBDay() {
return bDay;
}
public void setBDay(int day) {
this.bDay = day;
}
public int getBYear() {
return bYear;
}
public void setBYear(int year) {
this.bYear = year;
}
public int getAgeYear(){
int currentAgeYear = cYear -bYear;
return currentAgeYear;
}
public int getAgeMonth(){
int currentAgeMonth =cMonth - bMonth;
return currentAgeMonth;
}
public int getAgeDay(){
int currentAgeDay =cDay - bDay;
return currentAgeDay;
}
public String getdOB(TargetHeartRateCalculator patient) {
String dOB = String.format("%s/%s/%s",
patient.getBMonth(), patient.getBDay(), patient.getBYear());
return dOB;
}
public void setdOB(int dOB) {
this.dOB = dOB;
}
public static String displayAgeYears(TargetHeartRateCalculator patient) {
String ageYears = String.format("%s %s is %s Years old",
patient. getfName(), patient.getlName(), patient.getAgeYear());
return ageYears;
}
public void setAgeYears(int ageYears) {
this.ageYears = ageYears;
}
public double getMaxHeartRate() {
double maxHeartRate = (220 - getAgeYear()) ;
return maxHeartRate;
}
public void setMaxHeartRate(int maxHeartRate) {
this.maxHeartRate = maxHeartRate;
}
public double getLowTargetHearRate() {
lowTargetHearRate = getMaxHeartRate() * .5;
return lowTargetHearRate;
}
public void setLowTargetHearRate(int lowTargetHearRate) {
this.lowTargetHearRate = lowTargetHearRate;
}
public double getHighTargetHeartRate(){
highTargetHearRate = getMaxHeartRate() * .85;
return highTargetHearRate;
}
public void setHighTargetHearRate(){
this.highTargetHearRate = highTargetHearRate;
}
public static String displayTargetHeartRate(TargetHeartRateCalculator patient){
String hRateRange = String.format("%.2f BPM - %.2f BPM", patient.getLowTargetHearRate(), patient.getHighTargetHeartRate());
return hRateRange;
}
public static String displayMaxHeartRate(TargetHeartRateCalculator patient){
String mHeartRate = String.format("%.2f BPM", patient.getMaxHeartRate());
return mHeartRate;
}
public static String patientInfo(TargetHeartRateCalculator patient) {
String result = String.format("Patient Name: %s %s DOB: %d/%d/%d",
patient.getfName(), patient.getlName(), patient.getBMonth(), patient.getBDay(), patient.getBYear());
return result;
}
}
You should read all variables you need to construct your TargetHeartRateCalculator instance.
System.out.print("Please enter your first name: ");
String firstName = input.next();
System.out.print("Please enter your lastname: ");
String lastName = input.next();
System.out.print("Please enter your birthday day: ");
String birthdayDay = input.nextInt();
System.out.print("Please enter your birthday month: ");
String birthdayMonth = input.nextInt();
System.out.print("Please enter your birthday year: ");
String birthdayYear = input.nextInt();
TargetHeartRateCalculator patient = TargetHeartRateCalculator(firstName, lastName,
birthdayDay, birthdayMonth, birthdayYear);
Then, you can call your static methods after initialized your TargetHeartRateCalculator.
TargetHeartRateCalculator.displayTargetHeartRate(patient);
But, instead of putting everything into a class and using static methods in TargetHeartRateCalculator, you should divide your TargetHeartRateCalculator into two which can be Patient and TargetHeartRateCalculator.
Patient class can be like this:
import java.time.LocalDateTime;
public class Patient {
private String fName;
private String lName;
private int dOB;
private int bMonth;
private int bDay;
private int bYear;
private int ageYears;
private int currentYear = LocalDateTime.now().getYear();
private int currentMonth = LocalDateTime.now().getMonthValue();
private int currentDay = LocalDateTime.now().getDayOfMonth();
public Patient(String fName, String lName, int bMonth, int bDay, int bYear) {
this.fName = fName;
this.lName = lName;
this.bMonth = bMonth;
this.bDay = bDay;
this.bYear = bYear;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public int getbMonth() {
return bMonth;
}
public void setbMonth(int bMonth) {
this.bMonth = bMonth;
}
public int getbDay() {
return bDay;
}
public void setbDay(int bDay) {
this.bDay = bDay;
}
public int getbYear() {
return bYear;
}
public void setbYear(int bYear) {
this.bYear = bYear;
}
public int getAgeYear(){
return currentYear -bYear;
}
public int getAgeMonth(){
return currentMonth - bMonth;
}
public int getAgeDay(){
return currentDay - bDay;
}
}
The calculations will be in another class that take Patient object as an parameter and make calculations.
If I understand correctly, you're trying to get input into the constructor? I'll show one field since the rest are all the same
Scanner input = new Scanner(System.in);
System.out.print("Please enter your first name: ");
String fnInput = input.nextLine();
// repeat print and scan, as needed
TargetHeartRateCalculator patient1 = TargetHeartRateCalculator(fnInput); // add more parameters
Then you'll want have instance methods, not static methods with parameters.
public void patientInfo() {
System.out.printf("%s%n", this.getfName()); // for example
}
You call those methods like this
patient1.patientInfo();
And I think you should remove the print statements from the main method
in my recent uni work ive been given a task which i believe is to reassign values that have been set by getters and setters. The exact question is
" Edit the product’s main information that shares among all class such as ID,
Description, etc"
My attempt at this question is as followed.
public void editProductInformation() { //Standard level task 2 method 3
this.ID = 456890;
this.description = "Eggs";
this.recommendedUnitPrice = 10;
this.Unit = 6;
this.weight = 750;
}
}
this is also the code for the rest of the class
public class Product {
Scanner input = new Scanner(System.in);
protected int ID;
protected String description;
protected double recommendedUnitPrice;
protected double actualPrice;
protected int Unit = 1;
protected double weight;
protected LocalDate expiaryDate;
protected LocalDate expireDate;
public Product(int ID, String description, double recommendedUnitPrice, int unit, double weight, LocalDate expiarayDate) {
this.ID = ID;
this.description = description;
this.recommendedUnitPrice = recommendedUnitPrice;
this.Unit = unit;
this.weight = weight;
this.expiaryDate = expiarayDate;
}
public int getID() {
return this.ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getDescription() {
return this.description;
}
public void setDescripption(String description) {
this.description = description;
}
public double getRecommendedUnitPrice() {
return this.recommendedUnitPrice;
}
public void setRecommendedUnitPrice(double recommendedUnitPrice) {
this.recommendedUnitPrice = recommendedUnitPrice;
}
public int getUnit() {
return this.Unit;
}
public void setUnit(int unit) {
this.Unit = unit;
}
public double getWeight() {
return this.weight;
}
public void setWeight(double Weight) {
this.weight = Weight;
}
public LocalDate getExpiaryDate() {
return expiaryDate;
}
public void setExpiaryDate(LocalDate expiaryDate) {
this.expiaryDate = expiaryDate;
}
public void setPrice() {
System.out.println("Enter the price: ");
this.actualPrice = input.nextDouble();
}
public void setExpireDate() {
System.out.println("Enter the given date: ");
int day = input.nextInt();
int month = input.nextInt();
int year = input.nextInt();
LocalDate date = LocalDate.of(day, month, year);
this.expireDate = date;
}
public void comparePrice() { // Standard level task 2 method 1
if (recommendedUnitPrice == actualPrice) {
System.out.println("Price is equal");
} else if (recommendedUnitPrice < actualPrice) {
System.out.println("Price is less");
} else if (recommendedUnitPrice > actualPrice) {
System.out.println("Price is more");
}
}
public void verifyExpireProduct() { //Standard level task 2 method 2
if(expireDate == expiaryDate) {
System.out.println("Product is expired");
}
else System.out.println("Product is not expired");
}
I understand this question might not be explained well enough so i understand if people wish to downvote it. Any insight or help is much appreciated!
You can make an object of this class and then by using setter function defined in class you can set the value .
Product p1 = new Product();
p1.setId(5);
//This will set the Id to 5
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();