When I try to set my Dog object to dog2 and then have it print out the information I obtained for dog1, it keeps saying one of my variables is undefined. Below is my code for each component class as well as for main. If I take out dog2 and just call print for dog1, everything works as it should. I do not know what to do. I have been working on this for the past two days with no headway.
public class Owner {
private String ownerName;
private int ownerSSN;
private int ownerPhone;
public String getOwnerName () {
return ownerName;
}
public int getOwnerSSN () {
return ownerSSN;
}
public int getOwnerPhone () {
return ownerPhone;
}
public void setOwnerName (String own) {
this.ownerName = own;
}
public void setOwnerSSN (int ssn) {
this.ownerSSN = ssn;
}
public void setOwnerPhone (int phone) {
this.ownerPhone = phone;
}
// created the default constructor and the overloaded constructor
public Owner () {
ownerName = "John Doe";
ownerSSN = 0;
ownerPhone = 0;
}
public Owner (String own, int ssn, int phone) {
this.ownerName = own;
this.ownerSSN = ssn;
this.ownerPhone = phone;
}
}
public class DOB {
private int day;
private int month;
private int year;
public int getDay () {
return day;
}
public int getMonth () {
return month;
}
public int getYear () {
return year;
}
public void setDay (int day) {
this.day = day;
}
public void setMonth (int month) {
this.month = month;
}
public void setYear (int year) {
this.year = year;
}
// created the default constructor and the overloaded constructor for the DOB class
public DOB () {
day = 00;
month = 00;
year = 0000;
}
public DOB (int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
}
public class DogLicense {
private int licenseNum;
private int licenseYear;
private String licenseAuthority;
public int getLicenseNum () {
return licenseNum;
}
public int getLicenseYear () {
return licenseYear;
}
public String getLicenseAuthority () {
return licenseAuthority;
}
public void createLicenseNum (int license) {
licenseNum = (license * 705);
}
// created the default contructor and the overloaded constructor for the DogLicense class
public DogLicense () {
licenseNum = 0;
licenseYear = 0000;
licenseAuthority = "PA";
}
public DogLicense (int lNum, int lYear, String authority) {
this.licenseNum = lNum;
this.licenseYear = lYear;
this.licenseAuthority = authority;
}
}
public class Dog {
private String name;
private DogLicense licenseNum;
private Owner own;
private DOB dob;
// created the getters for the Dog Class
public String getName () {
return name;
}
public DogLicense getLicenseNum () {
return licenseNum;
}
public Owner getOwn () {
return own;
}
public DOB getDOB () {
return dob;
}
// created the setters for the Dog class
public void setName (String name) {
this.name = name;
}
public void setLicenseNum (DogLicense licenseNum) {
this.licenseNum = licenseNum;
}
public void setOwner (Owner own) {
this.own = own;
}
public void setDOB (DOB dob) {
this.dob = dob;
}
// created the default constructor and the overloaded constructor with references to other classes
public Dog () {
name = "New Puppy";
licenseNum = null;
own = null;
dob = null;
}
public Dog (String name, DogLicense licenseNum, Owner own, DOB dob) {
this.name = name;
this.licenseNum = licenseNum;
this.own = own;
this.dob = dob;
}
public void printDogInfo () {
System.out.println(this.own.getOwnerName() + ", here is the following information pertaining to your dog.");
System.out.println("Your dog's name is: " + this.name);
System.out.println(this.name + "'s licensing number is: " + this.licenseNum.getLicenseNum());
System.out.printf(this.name + "'s date of birth is: " + this.dob.getMonth () + "/" + this.dob.getDay () + "/" + this.dob.getYear ());
System.out.println();
System.out.println("Your phone number is: " + this.own.getOwnerPhone ());
System.out.println("Your social security number is: " + this.own.getOwnerSSN ());
}
}
import java.util.*;
public class TestDog {
#SuppressWarnings("resource")
public static void main(String[] args) {
Scanner animal = new Scanner (System.in);
Dog dog1 = new Dog ();
System.out.print("Please enter the name of your dog here: ");
String name = animal.next ();
dog1.setName (name);
System.out.println();
// created the information pertaining to the Owner
System.out.print("Please enter the name of the owner: ");
String own = animal.next ();
System.out.print("Please enter your 9 digit Social Security Number. Do not include dashes. ");
int ssn = animal.nextInt ();
System.out.print("Please enter your phone number. Please, do not include the area code or any dashes. ");
int phone = animal.nextInt ();
Owner owner1 = new Owner (own, ssn, phone);
dog1.setOwner (owner1);
System.out.println();
// created the information for Date of Birth
System.out.print("Please enter the day your dog was born (dd mm yyyy): ");
int day = animal.nextInt ();
int month = animal.nextInt ();
int year = animal.nextInt ();
DOB dob = new DOB (day, month, year);
dog1.setDOB (dob);
System.out.println();
// created information for Dog License
System.out.print("Please enter a one to four digit identifier number for your dog: ");
int license = animal.nextInt ();
System.out.print("Please enter the year you are obtaining your license number in: ");
int lYear = animal.nextInt ();
System.out.print("PLease enter the licensing authority in which you are registering your dog: ");
String authority = animal.next ();
System.out.println();
DogLicense dog1License = new DogLicense (license, lYear, authority);
dog1.setLicenseNum (dog1License);
dog1License.createLicenseNum(license);
dog1.printDogInfo ();
System.out.println();
System.out.println();
Dog dog2 = new Dog (name, license, own, dob);
dog2.printDogInfo ();
}
}
Related
I have an assignment but i have problem trying to do some part of it. Appreciate if anyone can give me a hand.
Assignment brief: https://pastebin.com/3PiqvfTE
Main Method: https://pastebin.com/J2kFzB3B
import java.util.ArrayList;
import java.util.Scanner;
public class mainMethod {
public static void main(String[] args) {
//scanner
Scanner scanner = new Scanner (System.in);
//subject object
Subject subject = new Subject (0,null,0);
System.out.println("How many subject do you want to enter: ");
int subjectNumber = scanner.nextInt();
for (int j = 0; j < subjectNumber; j++) {
//subject ID
System.out.println("Please enter the subject ID: ");
int subID = scanner.nextInt();
//subject Name
System.out.println("Please enter subject name: ");
String subName = scanner.next();
//subject fee
System.out.println("Please enter subject fee: ");
double subFee = scanner.nextDouble();
//add subject
subject.addSubject(subID, subName, subFee);
}
//display subject
System.out.println(subject.getSubject());
/*
//loop for part time teacher
System.out.println("Please enter how many part time teacher do you have: ");
int PTcounter = scanner.nextInt();
for (int i = 0; i < PTcounter; i++) {
*/
Teacher teach = new Teacher (0,null,null);
//teacher employee ID
System.out.println ("Please enter the teacher employee ID: ");
int tid = scanner.nextInt();
//teacher name
System.out.println("Please enter the teacher name: ");
String tname = scanner.next();
//teacher gender
System.out.println("Please enter the teacher gender: ");
String tgender = scanner.next();
//add teacher details
teach.addTeacher(tid, tname, tgender);
//display teacher details
System.out.println(teach.getTeacher());
//call address class
Address address = new Address (0,null,null,0);
//address house number
System.out.println("Please enter house number: ");
int addyNum = scanner.nextInt();
//address street name
System.out.println("Please enter street name: ");
String StreetName = scanner.next();
//address city
System.out.println("Please enter city: ");
String City = scanner.next();
//address post code
System.out.println("Please enter postcode: ");
int Postcode = scanner.nextInt();
//add address
address.addAddress(addyNum, StreetName, City, Postcode);
//display address
System.out.println(address.getAddress());
//call Part Time Salary class
PartTimeSalary ptSalary = new PartTimeSalary(0,0);
//max hours
System.out.println("Please enter maximum work hours: ");
int maxHours = scanner.nextInt();
//hourly rate
System.out.println("Please enter hourly rate: ");
double hourlyRate = scanner.nextDouble();
ptSalary.addPTSalary(maxHours, hourlyRate);
System.out.println(ptSalary.getHourlyRate());
//System.out.printf("Teacher details is %s, Subject details is %s, Address is %s", teach.toString(),subject.toString(),address.toString());
}
}
1st problem. I have a subject class and a teacher class. Teacher will be able to teach maximum of 4 subject. I have prompt user to enter subject details before entering teacher details, so when user enter teacher details they will be able to assign subject to teacher just by using the subjectID. I have problem implementing this. My subject is already store in an ArrayList but how to I connect this with teacher. And in the end the program will display what subject each teacher teaches.
Subject Class: https://pastebin.com/iBYFqYDN
import java.util.ArrayList;
import java.util.Arrays;
public class Subject {
private int subjectID;
private String subjectName;
private double fee;
private ArrayList <Subject> subjectList = new ArrayList <Subject>();
public Subject(int subjectID, String subjectName, double fee) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
}
public int getSubjectID () {
return subjectID;
}
public void setSubjectID (int subjectID) {
this.subjectID = subjectID;
}
public String getSubjectName () {
return subjectName;
}
public void setSubjectName (String subjectName) {
this.subjectName = subjectName;
}
public double getFee () {
return fee;
}
public void setFee (double fee) {
this.fee = fee;
}
#Override
public String toString() {
return "[subjectID=" + subjectID + ", subjectName=" + subjectName + ", fee=" + fee + "]";
}
public void addSubject (int subjectID, String subjectName, double fee) {
subjectList.add(new Subject(subjectID, subjectName, fee) );
}
public String getSubject () {
return Arrays.toString(subjectList.toArray());
}
}
Teacher class: https://pastebin.com/Np7xUry2
import java.util.ArrayList;
import java.util.Arrays;
public class Teacher {
private int employeeID;
private String name;
private String gender;
private ArrayList <Teacher> teacherDetailsList;
public Teacher (int employeeID, String name, String gender) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.teacherDetailsList = new ArrayList <Teacher>();
}
public int getEmployeeID () {
return employeeID;
}
public void setEmployeeID (int employeeID) {
this.employeeID = employeeID;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getGender () {
return gender;
}
public void setGender (String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "[employeeID=" + employeeID + ", name=" + name + ", gender=" + gender + "]";
}
public void addTeacher (int employeeID, String name, String gender) {
teacherDetailsList.add(new Teacher (employeeID,name,gender));
}
public String getTeacher () {
return Arrays.toString(teacherDetailsList.toArray());
}
}
2nd problem. Teacher will either be part time or full time teacher. Part time teacher will have a maximum work hour they can work and an hourly rate they will be paid for, so the final salary of part time teacher will be "maximum hours" multiply by "hourly rate". I have store "hourly rate" and "maximum work hours" in an ArrayList but how do I call them to make the multiplication then displaying at the end.
Part time salary class: https://pastebin.com/iGKpu87Y
import java.util.ArrayList;
public class PartTimeSalary {
private int maxHour;
private double hourlyRate;
private double hourlySalary;
private ArrayList <PartTimeSalary> PTSalary = new ArrayList <PartTimeSalary>();
private ArrayList <Double> finalHourlySalary = new ArrayList <Double>();
public PartTimeSalary (int maxHour, double hourlyRate) {
this.maxHour = maxHour;
this.hourlyRate = hourlyRate;
}
public int getMaxHours () {
return maxHour;
}
public void setMaxHour (int maxHour) {
this.maxHour = maxHour;
}
public double getHourlyRate () {
return hourlyRate;
}
public void setHourlyRate (double hourlyRate) {
this.hourlyRate = hourlyRate;
}
public double getHourlySalary() {
hourlySalary = hourlyRate*maxHour;
return hourlySalary;
}
public void addPTSalary (int maxHour, double hourlyRate) {
PTSalary.add(new PartTimeSalary(maxHour,hourlyRate));
}
public void FinalHourlySalary (double hourlySalary) {
hourlySalary = hourlyRate * maxHour;
finalHourlySalary.add(hourlySalary);
}
public ArrayList<Double> getFinalSalary () {
return (new ArrayList <Double>());
}
}
3rd question. I have an address class which is suppose to be part of the Teacher class. I can't seem to connect the address class with teacher class.
Address class: https://pastebin.com/s2HN5p80
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Address {
private int houseNum;
private String streetName;
private String city;
private int postcode;
private List <Address> address = new ArrayList <Address>();
public Address (int houseNum, String streetName, String city, int postcode) {
this.houseNum = houseNum;
this.streetName = streetName;
this.city = city;
this.postcode = postcode;
}
public int getHouseNum() {
return houseNum;
}
public void setHouseNum (int houseNum) {
this.houseNum = houseNum;
}
public String getStreetName() {
return streetName;
}
public void setStreetName (String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity (String city) {
this.city = city;
}
public int getPostcode() {
return postcode;
}
public void setPostcode (int postcode) {
this.postcode = postcode;
}
public void addAddress (int houseNum, String streetName, String city, int postcode) {
address.add(new Address (houseNum,streetName,city,postcode));
}
#Override
public String toString() {
return "[houseNum=" + houseNum + ", streetName=" + streetName + ", city=" + city + ", postcode="
+ postcode + "]";
}
public String getAddress () {
return Arrays.toString(address.toArray());
}
}
Thank you 😃😊
Question 1)
Put the "teacherDetailsList" and "subjectList" ArrayLists in the main method, not the consructors. Add the teachers and subjects in main methods, not constructors.
Add a new ArrayList called "mySubjects" as a field for the Teacher Class
Add the following 2 method to the Teacher class:
public Teacher (int employeeID, String name, String gender, ArrayList<Subject> s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects=s;
}
public Teacher (int employeeID, String name, String gender, Subject s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects.add(s);
}
public void addSubject(Subject s, boolean b){
if(mySubjects.size()<4)mySubjects.add(s);
else throw OutOfBoundsError;
}
public void removeSubject(Subject s, boolean b){
mySubject.remove(s);
}
public void addSubject(Subject s){
s.changeTeacher(s);
}
public void removeSubject(Subject s){
mySubject.remove(s);
}
Add the following methods & fields to Student class
private Teacher teacher;
public Subject(int subjectID, String subjectName, double fee, Teacher t) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
this.setTeacher(t);
}
public void setTeacher(Teacher t){
try{
t.addSubject(this);
teacher=t;
}
catch(OutOfBoundsError e){
System.out.println(t.getName()+" already has a full schedule.");
}
}
public void changeTeacher(Teacher t){
teacher.removeSubject(this);
teacher = t;
t.addSubject(this);
}
Question 2)
make a new double field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called maxHour in the class Subject
add a double field to the teacher class called salary. If the teacher is part-time, set this to 0 in the constructor.
add this method to Teacher class:
public double getSalary(){
if(salary!=0) return salary;
double s=0;
for(Subject i: mySubjects) s+=i.getFee()*i.getMaxHours();
return s;
}
You honestly no longer need the PartTimeSalary class now.
Question 3
make a new Address field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called myAddress in the class Teacher
Don't bother with the ArrayList stuff in your Address Class
Truthfully, I mixed some codes.
I need output like below:
Parking ticket #:
Fined amount:
Car issued to:
Issued by officer:
But here is current output:
Fined amount:
Car issued to:
Parking ticket #:null
Fined amount:
Issued by officer:
So looks like the main issue is with generating a parking ticket #
Code is
import java.util.Scanner;
public class ParkingTicketSimulator
{
public static void main(String[] args)
{
String make, model, color, license, name, badge;
int parkedMinutes, meterMinutes;
Scanner keyboard = new Scanner(System.in);
System.out.print("=== Parking Ticket Simulator ===\n\n");
System.out.print("---------\n");
System.out.print("Car Data\n");
System.out.print("---------\n\n");
System.out.print("Enter the car make: ");
make = keyboard.nextLine();
System.out.print("Enter the car model: ");
model = keyboard.nextLine();
System.out.print("Enter the car color: ");
color = keyboard.nextLine();
System.out.print("Enter the car license number: ");
license = keyboard.nextLine();
System.out.print("Enter minutes car has been parked:");
parkedMinutes = keyboard.nextInt();
System.out.print("\n----------\n");
System.out.print("Meter Data\n");
System.out.print("----------\n\n");
System.out.print("Enter minutes purchased by driver:");
meterMinutes = keyboard.nextInt();
keyboard.nextLine();
System.out.print("\n-------\n");
System.out.print("PO Data\n");
System.out.print("-------\n\n");
System.out.println();
System.out.print("Enter police officer's name:");
name = keyboard.nextLine();
System.out.print("Enter police officer's badge number:");
badge = keyboard.nextLine();
System.out.print("\n---------------------\n");
System.out.print("Parking Ticket Issued\n");
System.out.print("---------------------\n\n");
ParkedCar car = new ParkedCar(make,model,color,license,parkedMinutes);
ParkingMeter meter1 = new ParkingMeter (meterMinutes);
PoliceOfficer officer1 = new PoliceOfficer(name,badge,car,meter1);
System.out.println(officer1.getExpired(officer1));
}
public static class ParkedCar {
private String make;
private String model;
private String color;
private String license;
private int minutesParked;
public ParkedCar() {
make = "";
model = "";
color = "";
license = "";
minutesParked = 0;
}
public ParkedCar(ParkedCar carDetails){
make = carDetails.make;
model = carDetails.model;
color = carDetails.color;
license = carDetails.license;
minutesParked = carDetails.minutesParked;
}
public ParkedCar(String make, String model, String color, String license, int minutesParked){
this.make = make;
this.model = model;
this.color = color;
this.license = license;
this.minutesParked = minutesParked;
}
public void setMake (String make){
this.make = make;
}
public void setModel (String model){
this.model = model;
}
public void setColor (String color){
this.color = color;
}
public void setLicense (String license){
this.license = license;
}
public void minutesParked (int minutesParked){
this.minutesParked = minutesParked;
}
public String getMake(){
return make;
}
public String getModel(){
return model;
}
public String getColor(){
return color;
}
public String getLicense(){
return license;
}
public int getMinutesParked(){
return minutesParked;
}
public String toString(){
String str = "\nMake: " + make + "\nModel: " + model + "\nColor: " + color + "\nLicense: " + license + "\nMinutes parked: " + minutesParked;
return str;
}
}
public static class ParkingMeter {
private int minutes;
public ParkingMeter() {
minutes = 0;
}
public ParkingMeter(int minutes){
this.minutes = minutes;
}
public ParkingMeter (ParkingMeter minutesDetail){
minutes = minutesDetail.minutes;
}
public void setMinutes (int minutes){
this.minutes = minutes;
}
public int getMinutes(){
return minutes;
}
public String toString(){
String str ="\nMinutes: " + minutes;
return str;
}
}
public static class ParkingTicket{
private PoliceOfficer officer; //Calls the officer details.
private ParkedCar car;
private ParkingMeter meter;
private int fees;
public ParkingTicket(PoliceOfficer officer){
this.officer = new PoliceOfficer(officer);
this.meter = officer.getMeter();
this.car = officer.getParkedCar();
}
public ParkingTicket(){
}
public int fees(){
int time;
if (car != null || meter != null){
time = car.getMinutesParked() - meter.getMinutes() - 1;
fees = 25;
while (time > 0){
time = time - 1;
fees = fees+10;
}
}
return fees;
}
public String toString(){
if (fees() == 0 ){
String str = "There is no ticket issued.";
return str;
}
else{
String str = "\n" + officer +"\nTime over: " + (car.getMinutesParked() - meter.getMinutes()) + "\nThe fee is $" + fees();
return str;
}
}
}
public static class PoliceOfficer{
private String name;
private String badge;
private ParkedCar car;
private ParkingMeter meter;
private ParkingTicket ticket;
public PoliceOfficer(String name, String badge, ParkedCar carDetails, ParkingMeter time) {
this.name = name;
this.badge = badge;
car = new ParkedCar(carDetails);
meter = new ParkingMeter(time);
}
public PoliceOfficer(PoliceOfficer officerDetails){
name = officerDetails.name;
badge = officerDetails.badge;
car = officerDetails.car;
meter = officerDetails.meter;
}
public void setName (String name){
this.name = name;
}
public void setBadge (String badge){
this.badge = badge;
}
public String getName(){
return name;
}
public String getBadge(){
return badge;
}
public ParkedCar getParkedCar() {
return new ParkedCar(car);
}
public ParkingMeter getMeter(){
return new ParkingMeter(meter);
}
public ParkingTicket getExpired(PoliceOfficer officer){
if (meter.getMinutes() - car.getMinutesParked() < 0){
ticket = new ParkingTicket(officer);
return ticket;
}
else
ticket = new ParkingTicket();
return ticket;
}
public String toString(){
String str = "Officer Details\nOfficer's Name: " + name + "\nOfficer's Badge Number: " + badge + "\n\nCar Information: " + car + "\n\nMeter Information: " + meter;
return str;
}
}
I have the following code and I want to ask the user after an name that's already stored in the Arraylist and increase that (dogs) age by +1.
Here's the most important (I guess) part of the code. This is the Register Class.
import java.util.Scanner;
import java.util.ArrayList;
public class Register {
private Scanner keyboard = new Scanner(System.in);
private ArrayList<Dog> dogs = new ArrayList<>();
private String readString() {
return keyboard.nextLine();
}
public int readInt() {
int i = keyboard.nextInt();
keyboard.nextLine();
return i;
}
public double readDouble() {
double d = keyboard.nextDouble();
keyboard.nextLine();
return d;
}
public void registrateDog(){
System.out.println("Dogs name: ");
String name = readString();
System.out.println("Dogs breed: ");
String breed = readString();
System.out.println("Dogs age: ");
int age = readInt();
System.out.println("Dogs weight: ");
double weight = readDouble();
Dog newDog = new Dog(name, breed, age, weight);
dogs.add(newDog);
System.out.println(newDog.toString() + " is added");
}
public void increaseAge(){ //Here's the problem
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
private void exitProgram(){
System.out.println("Goodbye!");
keyboard.close();
}
private void run(){
setUp();
runCommandLoop();
exitProgram();
}
public static void main(String[] args){
new Register().run();
//setUp();
}
}
And
public class Dog {
private String name;
private String breed;
private int age;
private double weight;
private double tailLenght;
private String tax = "tax";
public Dog(String name, String breed, int age, double weight){
this.name = name;
this.breed = breed;
this.age = age;
this.weight = weight;
if (breed.equals(tax)) {
this.tailLenght = 3.7;
} else {
this.tailLenght = (age*weight) / 10;
}
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed(){
return breed;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public int newAge(){
return age = age + 1;
}
public double getWeight(){
return weight;
}
public double getTailLenght(){
return tailLenght;
}
public String toString()
{ return String.format("%s, %s, %d years old, %.1f kg, "
+ "tail lenght %.1f cm", name, breed, age, weight, tailLenght);
}
}
So in this code you're finding the Dog by its name. Which is great.
public void increaseAge() {
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
Inside of your Dog class you have a method which returns the age, what you want to do is modify it to:
public int newAge(){
this.age++; // This will take the current age of the dog and add one to it
}
Now going back to the increaseAge() method you want to modify the for loop to look like:
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
dogs.get(i).newAge(); // This will update the Dogs age by 1 year
System.out.println("Dog " + dogs.get(i).getName() + " is now " + dogs.get(i).getAge());
return;
}
Where are you incrementing the age ? Call the newAge() method as you have defined in the Dog class.`
Dog dog = dogs.get(i);
dog.setAge(dog.newAge());
dogs.set(i,dog);`
We've fetched the particular dog who's details matched. Then we incremented it's age and set it back in the list at that position.
I'm writing code for an application that keeps track of a student’s food purchases at a campus cafeteria. There's two classes - Student, which holds overloaded constructors & appropriate getter & setter methods; and MealCard, which holds a class variable to track the number of meal cards issued, appropriate getter & setter methods, a purchaseItem() method, a purchasePoints() method & an overriddden toString() method. There's a Tester class also.
In my MealCard class, the methods are written but in the Tester when I call them, they don't work correctly. I want to get the itemValue from the user but how do I do this in the MealCard class?
Same goes for the purchasePoints method, how do I get the topUpValue from user in MealCard class?
Code so far is:
public class Student {
// Instance Variables
private String name;
private int age;
private String address;
// Default Constructor
public Student() {
this("Not Given", 0, "Not Given");
}
// Parameterized constructor that takes in values
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress(){
return address;
}
public void setAddress(String address) {
this.address = address;
}
// toString() to be overriden
#Override
public String toString() {
return "Name: " + this.name + "\n" + "Age: " + this.age + "\n" + "Address: " + this.address;
}
}
`
public class MealCard extends Student {
static int numberOfMealCards;
private final static int DEFAULT_BALANCE = 1000;
private int itemValue;
private int topUpValue;
public int newBalance;
// Getters and Setters
public int getItemValue() {
return itemValue;
}
public void setItemValue(int itemValue) {
this.itemValue = itemValue;
}
public int getTopUpValue() {
return topUpValue;
}
public void setTopUpValue(int topUpValue) {
this.topUpValue = topUpValue;
}
// purchaseItem method for when students buy food
public int purchaseItem() {
newBalance = DEFAULT_BALANCE - itemValue;
return newBalance;
}
// purchasePoints method for students topping up their meal card balance
public int purchasePoints() {
newBalance = DEFAULT_BALANCE + topUpValue;
return newBalance;
}
// Overriden toString method
#Override
public String toString() {
return super.toString() + "Meal Card Balance: " + this.newBalance + "\n" + "Number of Meal Cards: " + numberOfMealCards;
}
}
`
import java.util.Scanner;
public class TestMealCard {
public static void main(String[] args) {
// Create instances of MealCard class
MealCard student1 = new MealCard();
MealCard student2 = new MealCard();
Scanner keyboard = new Scanner(System.in);
System.out.println("Name: ");
student1.setName(keyboard.nextLine());
System.out.println("Age: ");
student1.setAge(keyboard.nextInt());
System.out.println("Address: ");
student1.setAddress(keyboard.nextLine());
System.out.println("Meal Card Balace: ");
student1.newBalance = keyboard.nextInt();
System.out.println("Number of Meal Cards Issued: ");
student1.numberOfMealCards = keyboard.nextInt();
System.out.println("Name: ");
student2.setName(keyboard.nextLine());
System.out.println("Age: ");
student2.setAge(keyboard.nextInt());
System.out.println("Address: ");
student2.setAddress(keyboard.nextLine());
System.out.println("Meal Card Balace: ");
student2.newBalance = keyboard.nextInt();
System.out.println("Number of Meal Cards Issued: ");
student2.numberOfMealCards = keyboard.nextInt();
// Call purchaseItem
student1.purchaseItem();
// Call purchasePoints
student2.purchasePoints();
// Call tString to output information to user
}
}
In order to set the itemValue from the user you need to get get that input from the user using this setItemValue() method.
Ex.
System.out.print("Please enter the item value: ");
student1.setItemValue(keyboard.nextInt());
or
int itemVal = 0;
System.out.print("Please enter the item value: ");
itemVal = keyboard.nextInt();
student1.setItemValue(itemVal);
as for the other method call just call the setter for toUpValue.
Ex.
System.out.print("Please enter the item value: ");
student1.setTopUpValue(keyboard.nextInt());
or
int toUpVal = 0;
System.out.print("Please enter the item value: ");
itemVal = keyboard.nextInt();
student1.setTopUpValue(topUpVal);
Hope that helps =).
import cs1.Keyboard;
import java.util.Scanner;
class Person
{
private String name;
private String persnr;
private String adress;
private int age;
public Person(String _name, String _persnr, String _adress, int _age)
{
name = name;
persnr = persnr;
adress = adress;
age = age;
}
public void byterNamn(String _name)
{
name = _name;
}
public void byterAdress(String _adress)
{
adress = _adress;
}
public void fyllerAr()
{
age = age + 1;
}
public String hamtaNamn()
{
return name;
}
public String hamtaPersonnmmer()
{
return persnr;
}
public String hamtaAdress()
{
return adress;
}
public int hamtaAlder()
{
return age;
}
public String toString()
{
String _toString;
_toString = "Namn: " + name + "\nÃ…lder: " + age;
_toString = _toString + "\nPersonnummer: " + persnr + "\nAdress: " + adress;
return _toString;
}
public p1()
{
System.out.print("namn: ");
name = Keyboard.readString();
System.out.print( "adress: " );
String adress = Keyboard.readString();
System.out.print( "Ã¥lder: " );
Integer age = new Integer();
age.parseInt(Keyboard.readint());
System.out.print( "personnummer: " );
String persnr = Keyboard.readString();
}
public p2()
{
System.out.print("namn: ");
name = Keyboard.readString();
System.out.print( "adress: " );
String adress = Keyboard.readString();
System.out.print( "Ã¥lder: " );
Integer age = new Integer();
age.parseInt(Keyboard.readint());
System.out.print( "personnummer: " );
String persnr = Keyboard.readString();
}
public static void main(String[] args)
{
String name = Keyboard.readString();
String persnr = Keyboard.readString();
String adress = Keyboard.readString();
int age = Keyboard.readint();
Person p1 = new Person(name, age, adress, personnummer);
String name = Keyboard.readString();
String persnr = Keyboard.readString();
String adress = Keyboard.readString();
int age = Keyboard.readint();
Person p2 = new Person(name, age, adress, personnummer);
}
}
hello.
I try to do so it is 2 people. where you should enter the age, name, address of both people and then print it after you enter what you want when the program runs. and i wondering how do i do return on public p1() and public p2() so i can do it. Or is it a easier way to do it?
This code does not compile. public p1() and public p2() are not valid method declarations. You must at least add a method return type after the public and before the method name, for example:
public Person p1()
Then I guess what you want to do is return a Person object from each of those two methods. Inside the method you must create a new Person object and then return it from the method:
return new Person(name, persnr, adress, age);
See Defining Methods and Returning a Value from a Method in Oracle's Java Tutorials.