So I have this zoo program where I want to have a list of rooms in a zoo, and a list of cats in each room.
I have 3 classes: Felid, Housecat and Wildcat - Housecat and Wildcat extend Felid. depending on the literal class of animal (right now I have tiger, persian, siamese and cheetah - tiger and cheetah extend wildcat, persian and siamese extend housecat) certain attributes will be automatically assigned.
Class diagram - http://i.imgur.com/VTSNRVA.jpg
For example these are the fields for felid:
String speciesName;
String furColour;
String gender;
int weightPounds;
boolean packAnimal;
String habitat;
int age;
These are the fields for housecat:
String ownerName;
String catName;
boolean feral;
These are the fields for wildcat:
boolean manEater;
In my constructor for housecat I have
if(catName == null || catName.equals("")){
feral = true;
}
and if the cat's feral, when the user creates a HouseCat with a cat name and uses 'printCatInfo()':
#Override
public void printCatInfo(){
if(feral){
System.out.println("feral" + "\n" + speciesName + "\n" + furColour + "\n" + gender +
"\n" + weightPounds + "lbs\n" + "is not a pack animal" + "\n" + habitat + "\n" + age + " years old (human)");
}
else{
System.out.println("owner name is: " + ownerName + "\n" + "cat name is: " + catName + "\n" + speciesName + "\n" + furColour + "\n" + gender +
"\n" + weightPounds + "lbs\n" + "is not a pack animal" + "\n" + habitat + "\n" + age + " years old (human)" + "\n");
}
}
It won't print its name.
feral
siamese
White or grey abdomen with black legs, face and tail
male
8lbs
is not a pack animal
urban
7 years old (human)
The trouble is that it counted all cats as feral which I assumed was because the list I used for the list of cats is:
ArrayList<Felid> catList = new ArrayList<Felid>();
So I guess the catName will always be null because the housecats that are added to the list will just count as type 'felid'.
How do I create a list that I can throw all of the cats into and but still treat them as their respective classes?
edit: thanks for pointing out the assignment operator error, it's still only printing feral though
Final edit: Thank you very much to 'DoubleDouble' for pointing out how to use 'Super()' to me - that's not what I expected the problem was. This was the problem:
public class Siamese extends HouseCat{
public Siamese(int weightPounds, int age, String ownerName, String catName, String gender){
this.speciesName = "siamese";
this.furColour = "White or grey abdomen with black legs, face and tail";
this.ownerName = ownerName;
this.catName = catName;
this.weightPounds = weightPounds;
this.age = age;
this.gender = gender;
}
}
New code:
public class Siamese extends HouseCat{
public Siamese(int weightPounds, int age, String ownerName, String catName, String gender){
super(catName);
this.speciesName = "siamese";
this.furColour = "White or grey abdomen with black legs, face and tail";
this.ownerName = ownerName;
this.catName = catName;
this.weightPounds = weightPounds;
this.age = age;
this.gender = gender;
}
}
if(feral = true){
This is an assignment statement, not a comparison. Use ==
In this line:
if(feral = true){
You assigned true to feral. You used the assignment operator =. The comparison operator is ==. However, feral is already a boolean, so you can use feral itself in the condition.
if (feral) {
Your constructors seem to the following (correct me if I am wrong):
public Siamese(int weightPounds, int age, String ownerName, String catName, String gender)
{
this.weightPounds = weightPounds;
this.age = age;
this.ownerName = ownerName;
this.catName = catName;
this.gender = gender;
}
public HouseCat()
{
if(catName == null || catName.equals(""))
{
feral = true;
}
}
Since ownerName, catName, and feral are all a part of the HouseCat class, it is best to let the HouseCat constructor handle those fields.
public HouseCat(String ownerName, String catName)
{
this.ownerName = ownerName;
this.catName = catName;
if(catName == null || catName.equals(""))
{
feral = true;
}
}
Siamese looks like this then:
public Siamese(int weightPounds, int age, String ownerName, String catName, String gender)
{
super(ownerName, catName);
this.weightPounds = weightPounds;
this.age = age;
this.gender = gender;
}
Related
Hi I'm working on a java program that allows user to input their information such as name, car model, capacity etc, later they can see their information in a list:
Car Registration Listing
Reg No. Name IC No. Plate No. Color Year Make Model Capacity
1001 John Wayne 111111111 ABC123 Blue 2010 Toyota Vios 1.5
1002 Bea Arthur 222222222 WEA888 Red 2010 Nissan Teana 2.0
1003 Meg Ryan 333333333 PBL168 Black 2011 Honda City 1.6
1004 Jane Doe 444444444 BBB777 White 2011 Nissan Teana 2.0
1005 Al Johnson 555555555 CAT118 Green 2012 Toyota Vios 1.5
1006 Ned Beatty 666666666 TV798 Blue 2012 Toyota Vios 1.5
Below is the code:
public class CarRegistrationListing {
int regNo;
String name;
int icNo;
String plateNo;
String color;
int year;
String make;
String model;
double capacity;
public CarRegistrationListing(int regNo, String name, int icNo, String plateNo, String color, int year, String make, String model, double capacity) {
this.regNo = regNo;
this.name = name;
this.icNo = icNo;
this.plateNo = plateNo;
this.color = color;
this.year = year;
this.make = make;
this.model = model;
this.capacity = capacity;
}
public int getRegNo() {
regNo++;
return regNo;
}
public String getName(){
return name;
}
public int getIcNo(){
return icNo;
}
public String getPlateNo(){
return plateNo;
}
public String getColor(){
return color;
}
public int getYear(){
return year;
}
public String getMake(){
return make;
}
public String getModel(){
return model;
}
public double getCapacity(){
return capacity;
}
public void setName(String name){
this.name = name;
}
public void setIcNo(int icNo){
this.icNo = icNo;
}
public void setPlateNo(String plateNo){
this.plateNo = plateNo;
}
public void setColor(String color){
this.color = color;
}
public void setYear(int year){
this.year = year;
}
public void setMake(String make){
this.make = make;
}
public void setModel(String model){
this.model = model;
}
public void setCapacity(double capacity){
this.capacity = capacity;
}
#Override
public String toString() {
return "CarRegistrationListing{" + "regNo=" + regNo + ", name=" + name + ", icNo=" + icNo + ", plateNo=" + plateNo + ", color=" + color + ", year=" + year + ", make=" + make + ", model=" + model + ", capacity=" + capacity + '}';
}
}
This is for test run:
import java.util.Scanner;
public class TestCarReg {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many records do you want to register: ");
int record = scan.nextInt();
CarRegistrationListing car = new CarRegistrationListing(1000, "", 0, "", "", 0, "", "", 0.0);
for (int i = 0; i < record; i++) {
String[] carType = {"Toyota Vios", "Nissan Teana", "Honda City"};
System.out.println("Car Type:");
for (String carType1 : carType) {
System.out.println(carType1);
}
System.out.print("Choose your car type(1 to 3): ");
int type = scan.nextInt();
String make;
String model;
switch (type) {
case 1:
make = "Toyota";
model = "Vios";
break;
case 2:
make = "Nissan";
model = "Teana";
break;
default:
make = "Honda";
model = "City";
break;
}
System.out.print("Enter name: ");
String name = scan.nextLine();
car.setName(name);
scan.nextLine();
System.out.print("Enter IC number: ");
int icNo = scan.nextInt();
car.setIcNo(icNo);
System.out.print("Enter plate number: ");
String plateNo = scan.next();
car.setPlateNo(plateNo);
System.out.print("Enter color: ");
String color = scan.next();
car.setColor(color);
System.out.print("Enter year: ");
int year = scan.nextInt();
car.setYear(year);
car.setMake(make);
car.setModel(model);
System.out.print("Enter capacity: ");
double capacity = scan.nextDouble();
car.setCapacity(capacity);
}
System.out.println("Car Registration Listing");
for (int i = 0; i < record; i++) {
System.out.println("Reg No.\tName\t\tIC No.\tPlate No.\tColor\tYear\tMake\tModel\tCapacity");
System.out.println(car.getRegNo() + "\t" + car.getName() + "\t\t" + car.getIcNo() + "\t" + car.getPlateNo() + "\t\t" + car.getColor() + "\t" + car.getYear() + "\t" + car.getMake() + "\t" + car.getModel() + "\t" + car.getCapacity());
}
}
}
I tried printing the output according to the sample shown above, but I got this in my output:
debug: How many records do you want to register: 2
Car Type: Toyota Vios Nissan Teana Honda City
Choose your car type(1 to 3): 1
Enter name: william Sebastian
Enter IC number: 1111
Enter plate number:AC1212
Enter color: Red
Enter year: 2010
Enter capacity: 1.0
Car Type: Toyota Vios Nissan Teana Honda City
Choose your car type(1 to 3): 1
Enter name: wong ang soon
Enter IC number: 2222
Enter plate number: AR1234
Enter color: White
Enter year: 2013
Enter capacity: 2.0
Reg No. Name IC No. Plate No. Color Year Make Model Capacity
1001 2222 AR1234 White 2013 Honda City 2.0
Reg No. Name IC No. Plate No. Color Year Make Model Capacity
1002 2222 AR1234 White 2013 Honda City 2.0
The name can't be printed and the variables for first person were disappeared, I tried to use array for CarRegistrationListing but it caused error.
I would appreciate if someone can point out my mistakes.
Thank you so much!
the variables for first person were disappeared
It is because the variable car is overwritten inside the for loop every time when you enter a new entry.
To show the values for first person, you can create an ArrayList before the data-entry for loop
List<CarRegistrationListing> carList = new ArrayList<CarRegistrationListing>();
And store the values into the ArrayList at the end of for loop
carList.add(car);
At last, you may print the values from ArrayList as below.
System.out.println("Reg No.\tName\t\tIC No.\tPlate No.\tColor\tYear\tMake\tModel\tCapacity");
for (CarRegistrationListing car : carList) {
System.out.println(car.getRegNo() + "\t" + car.getName() + "\t\t" + car.getIcNo() + "\t" + car.getPlateNo() + "\t\t" + car.getColor() + "\t" + car.getYear() + "\t" + car.getMake() + "\t" + car.getModel() + "\t" + car.getCapacity());
}
The name can't be printed
It is because the newline character is not consumed by nextInt() causing input not properly read, you can add scan.nextLine() before reading the name from input.
You may find more information from here, as mentioned by #user16320675 in the comments
scan.nextLine();
String name = scan.nextLine();
I also noticed you would like to have autoincrement for RegNo.
Instead of adding regNo++ in getter function, I will suggest to create a static member for generating unique regNo inside Constructor
More information at: Java create a unique ID for each instantiated object using instance methods instead of class/static methods
static int globalRegNo = 1000;
public CarRegistrationListing(int regNo, String name, int icNo, String plateNo, String color, int year, String make, String model, double capacity) {
this.regNo = globalRegNo++;
this.name = name;
this.icNo = icNo;
this.plateNo = plateNo;
this.color = color;
this.year = year;
this.make = make;
this.model = model;
this.capacity = capacity;
}
I am trying to print the grade for the student subclass, i feel like i need some type of if statement or array.I am trying to make a code that can be passed a number such as 3 for "Junior" but can also be called through a code such Student.JUNIOR to print the grade level junior. my desired output is:
class Person {
String name;
String campus;
String phone;
String email;
int FRESHMAN = 1;
int SOPHMORE = 2;
int JUNIOR = 3;
int SENIOR = 4;
public Person(String n, String cam, String cell, String mail) {
name = n;
campus = cam;
phone = cell;
email = mail;
}
public String toString() {
return "Name:" + name + "; Campus:" + campus + "; Phone:" + phone + "; Email:" + email + " ";
}
}
class Student extends Person {
int grade;
public Student(String n, String cam, String cell, String mail, int grade) {
super(n, cam, cell, mail);
}
public String toString() {
return super.toString() + "\nClass:";
}
}
class Employee extends Person {
private String title;
public Employee(String n, String cam, String cell, String mail, String position) {
super(n, cam, cell, mail);
title = position;
}
public String toString() {
return super.toString() + "\nTitle:" + title;
}
}
public class Exam3c {
public static void main(String[] args) {
String name = "David";
String campus = "Terry";
String phone = "302-573-3254";
String email = "Genos#edu";
Person P1 = new Person(name, campus, phone, email);
System.out.println("P1: \n" + P1);
Student S1 = new Student(name, campus, phone, email, 1);
System.out.println("S1: \n" + S1);
Student S2 = new Student("Bill While", "Nowhere", "012-345-6789", "bw#nowhere.edu", 3);
System.out.println("S2: \n" + S2);
Employee E1 = new Employee(name, campus, phone, email, "Faculty");
System.out.println("E1: \n" + E1);
}
}
I think you're looking for enums. They have a lot of very useful features; in addition to being nicely type safe in a way that "Magic Ints" are not, you can also fairly fluidly treat them as Strings for debugging.
I created a class called "Person" here it is: (ignore the toString. I haven't done anything with that yet)
public class Person {
public String firstName;
public String middleName;
public String lastName;
public Person() {
firstName = "first";
middleName = "middle";
lastName = "last";
}
public Person(String first, String middle, String last) {
firstName = first;
middleName = middle;
lastName = last;
}
public String toString() {
return (firstName + " " + middleName + " " + lastName);
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
}
And then I created an implementation class in a new file, this is it:
import java.util.*;
public class TestProgPerson
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
String first;
String middle;
String last;
Person name = new Person("Joe", "Smith", "Blow");
System.out.println("Name: " + name);
System.out.println("Please enter a last name, to check if it corresponds with the persons last name: " );
last = console.nextLine();
if (last == (objectReference.lastName))
System.out.println("The last name you entered matches the persons last name");
else
System.out.println("The last name you entered does not match the persons last name");
}
}
So what I want it to do is this: Have an object with the first name, middle name, and last name. Output that name. (The program works this far). Then I want to have the user enter a last name, and the program checks to see if the entered last name is the same as the last name in the object. How do I go about calling just an individual string from that object?
Here you are calling the name object of the class but not any field of that class.
System.out.println("Name: " + name);
You can call fields here by using the object of the class and the dot operator.
For Example.
System.out.println("Name: " + name.firstName + " " + name.middleName + " " + name.lastName);
Moreover because strings are Objects and should be compared with the equals method.
I am currently writing a program that models an employee as a way to get started in object oriented programming. It gets a name, hire date, and address of each employee, and then must display the information
My current program has no compile errors, but I am confused as to how I would go about printing the information in a neat manner. Thanks!
public class Unit10Assignment1
{
public static void main( String [] args )
{
int numEmployees = Input.getInt("How many employees are you storing?");
Employee database[] = new Employee[numEmployees];
for( int i = 0; i < numEmployees; i++ )
{
String firstName = Input.getString("What is an employee's first name?");
String lastName = Input.getString("What is their last name?");
String street = Input.getString("What street do they live on?");
String city = Input.getString("What city do they live in?");
String state = Input.getString("What state do they live in?(2 characters)");
String zip = Input.getString("What is their zipcode?");
int month = Input.getInt ("In what month was he/she hired?(number)");
int day = Input.getInt ("On what day was he/she hired(number)");
int year = Input.getInt ("In what year was he/she hired?(number)");
database[i] = new Employee(firstName, lastName, street, city, state, zip, month, day, year);
}
}
}
class Employee
{
Name Name;
Address Address;
Date Date;
Employee( String firstName, String lastName, String street, String city, String state, String zip, int month, int day, int year)
{
Name = new Name( firstName, lastName );
Address = new Address( street, city, state, zip );
Date = new Date( month, day, year );
}
}
class Name
{
String firstName = " ";
String lastName = " ";
public Name(String newFirstName, String newLastName)
{
firstName = newFirstName;
lastName = newLastName;
}
public String getFirst()
{
return firstName;
}
public String getLast()
{
return lastName;
}
}
class Address
{
String street = " ";
String city = " ";
String state = " ";
String zip = " ";
public Address(String newStreet, String newCity, String newState, String newZip)
{
street = newStreet;
city = newCity;
state = newState;
zip = newZip;
}
public String getStreet()
{
return street;
}
public String getCity()
{
return city;
}
public String getState()
{
return state;
}
public String getZip()
{
return zip;
}
}
class Date
{
int month = 0;
int day = 0;
int year = 0;
public Date(int newMonth, int newDay, int newYear)
{
month = newMonth;
day = newDay;
year = newYear;
}
public int getMonth()
{
return month;
}
public int getDay()
{
return day;
}
public int getYear()
{
return year;
}
}
Having trouble formatting, hopefully you can understand it. If there are any problems with my current code, pointing them out to me would be appreciated. Also, my instructor uses his own class to get user input so no need to worry about that.
For pretty printing an objects contents, I prefer overriding the toString method.
You could override the toString-method in Name, Address and Date, and let Employee use these methods in its own toString.
E.g:
Name
#Override
public String toString() {
return firstName + " " + lastName;
}
Address
#Override
public String toString() {
return street + ", " + city + ", " + state + ", " + zip;
}
Date
#Override
public String toString() {
return String.valueOf(month) + "." +
String.valueOf(day) + "." +
String.valueOf(year);
}
Employee
#Override
public String toString() {
return name.toString() + "\n" +
date.toString() + "\n" +
address.toString();
}
by the way, you can use astyle to format your code
I am very new with java programming and I am close to finishing a very big project for me. I am trying to make an employee registry that simply relays information back. Whenever I enter the info it just returns stuff like Name#5a965654. My classes are below and any help would be appreciated.
Main:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employees[] = new Employee[employeeCount];
String firstName;
String lastName;
String street;
String city;
String state;
String zipCode;
String monthHired;
String dateHired;
String yearHired;
int employeeID;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the first name of employee " + (x + 1));
firstName = Input.nextLine();
System.out.println("Please enter the last name of employee " + (x + 1));
lastName = Input.nextLine();
System.out.println("Please enter the street of employee " + (x + 1));
street = Input.nextLine();
System.out.println("Please enter the city of employee " + (x + 1));
city = Input.nextLine();
System.out.println("Please enter the state of employee " + (x + 1));
state = Input.nextLine();
System.out.println("Please enter the zip code of employee " + (x + 1));
zipCode = Input.nextLine();
System.out.println("Please enter the month hired for employee " + (x + 1));
monthHired = Input.nextLine();
System.out.println("Please enter the date hired for employee " + (x + 1));
dateHired = Input.nextLine();
System.out.println("Please enter the year hired for employee " + (x + 1));
yearHired = Input.nextLine();
Name name = new Name(firstName, lastName);
name.setName(firstName, lastName);
Address address = new Address(street, city, state, zipCode);
DateOfHire hireDate = new DateOfHire(monthHired, dateHired, yearHired);
employees[x] = new Employee(name, address, hireDate, x);
}
for(int x = 0; x < employeeCount; x++)
{
employees[x].printInfo(x);
}
}
}
Employee class:
public class Employee
{
private Name name;
private Address address;
private DateOfHire hireDate;
int ID;
public Employee()
{
}
public Employee(Name name, Address address, DateOfHire hireDate, int x)
{
this.name = name;
this.address = address;
this.hireDate = hireDate;
this.ID = x;
}
public void printInfo(int x)
{
System.out.println("Employee-" + (x + 1));
System.out.println("Name: " + this.name);
System.out.println("Address: " + this.address);
System.out.println("Date of Hire: " + this.hireDate);
}
}
Format of Name, DateHired, and Address classes:
public class Name
{
private String firstName;
private String lastName;
public Name()
{
}
public Name(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public void setName(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getName()
{
return firstName + " " + lastName;
}
}
A Name is not the same as a String, so when you print this.name in Employee.printInfo, it prints Name#[numbers], indicating that what you're printing is a Name object at the location described by the numbers.
Try replacing that line with
System.out.println("Name: " + this.name.getName());
Also, you'll need to do something similar for the Address and DateOfHire, but I don't know what you have implemented for those, so I can't really say what specifically to do. Essentially, though, you'll need a method that gives a string representation of whatever object it is that you want to print.
All classes in Java extend from the java.lang.Object which has a method toString(). This method is implemented as
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
Whenever you call
System.out.println("Name: " + this.name);
String concatenation is done by implicitly calling the toString() method of your instance. If your class doesn't implement (override) the toString() method, then Object's implementation is used.
See the String Conversion rules in the Java Language Specification.
Otherwise, the conversion is performed as if by an invocation of the
toString method of the referenced object with no arguments; but if the
result of invoking the toString method is null, then the string "null"
is used instead.
Since your Name class does not have a toString() method, then its parent class' method is called, ie. Object#toString() and you get the output you see.
You should override the toString() method in all your classes. For example,
public class Name
{
private String firstName;
private String lastName;
public Name()
{
}
public Name(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public void setName(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String toString()
{
return firstName + " " + lastName;
}
public String getName()
{
return firstName + " " + lastName;
}
}
It does not matter than toString() and getName() return the same thing in this case. You have to follow the language spec.
You should implement String toString() method if you wanna print an object