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.
Related
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;
}
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
All,
Below code is working fine with the ArrayList. could you please help me on how to get user input for name gender and amountSpent (array size [4]), then split it by spaces so that it will have String, String and double.
Also, How to display the result of only the customer who has higher amount Spent then the other Customers.
thank you in advance!
Regards,
Viku
import java.util.Comparator;
public class Customer implements Comparable <Customer>{
public String name,gender;
public double amountSpent;
public Customer(String name, String gender, double amountSpent) {
super();
this.name = name;
this.gender = gender;
this.amountSpent = amountSpent;
}
public String getCustomername() {
return name;
}
public void setCoustomername(String name) {
this.name = name;
}
public String getgender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public double getamountSpent() {
return amountSpent;
}
public void setamountSpent(double amountSpent) {
this.amountSpent = amountSpent;
}
public static Comparator <Customer> CustomerNameComparator = new Comparator<Customer>() {
public int compare(Customer c1, Customer c2) {
String custName1 = c1.getCustomername().toUpperCase();
String custName2 = c2.getCustomername().toUpperCase();
//ascending order
//return custName1.compareTo(custName2);
//descending order
return custName2.compareTo(custName1);
}
};
public static Comparator <Customer> CustomerAmountSpentComparator = new Comparator<Customer>() {
public int compare(Customer aS1, Customer aS2) {
int custamtspent1 = (int) aS1.getamountSpent();
int custamtSpent2 = (int) aS2.getamountSpent();
//ascending order sort
// return custamtspent1 - custamtSpent2;
//descending order sort
return custamtSpent2 - custamtspent1;
}
};
#Override
public int compareTo(Customer o) {
return 0;
}
#Override
public String toString() {
return " Customer Name : " + name + ", Gender : " + gender + ", Amount Spent : " + amountSpent + "";
}
}
and Main Program:
import java.util.ArrayList;
import java.util.Collections;
public class MainProg {
public static void main(String args[]){
String nL = System.lineSeparator();
try {
ArrayList<Customer> arraylist = new ArrayList<Customer> ();
arraylist.add(new Customer ("Louis","Male", 4567.76));
arraylist.add(new Customer ("Daniela","Female", 7653.67));
arraylist.add(new Customer ("Jenny","Female", 3476.98));
arraylist.add(new Customer ("Arijit","Male", 9876.44));
System.out.println("Customer Name Decending Sort: " + nL);
Collections.sort(arraylist, Customer.CustomerNameComparator);
for (Customer str: arraylist) {
System.out.println(str);
}
System.out.println(nL + "Custmer Amount Spent [Hight to Low] Sorting: " + nL);
Collections.sort(arraylist, Customer.CustomerAmountSpentComparator);
for (Customer str: arraylist){
System.out.println(str);
}
System.out.println(nL + "Highest Amount Spent Custmer Detail: " + nL);
}
catch (Exception e){
System.out.println("Error: " + e);
}
finally {
System.out.println(nL + "Report Completed!");
}
}
}
OPTION 1 (suggested):
If the user is to input the data, why do you need to split it up? Just do as follows:
System.out.println("Name:");
name = scn.nextLine();
System.out.println("Gender:");
gender = scn.nextLine():
System.out.println("Amt:");
amt = scn.nextDouble();
Customer c1 = new Customer (name,gender, amt);
OPTION 2:
Alternatively, if you want user to input everything in one single line (separated by spaces), just do this:
System.out.println("Input name, gender, amt:");
name = scn.next();
gender = scn.next():
amt = scn.next();
Customer c1 = new Customer (name,gender, amt);
PROGRAM OUTPUT: Input name, gender, amt: John Male 33.50
OPTION 3 (requested by you):
Lastly if you still insist of doing a split by space, and you want to accept the user input in one string separated by spaces:
System.out.println("Input name, gender, amt:");
input = scn.nextLine();
String[] token = input.split(" ");
String name = token[0];
String gender = token[1];
double amt = Double.parseDouble(token[2]);
Customer c1 = new Customer (name,gender, amt);
PROGRAM OUTPUT: Input name, gender, amt: John Male 33.50
For your first question (if I have understood right), you want to take a user input as string:
Dave Male 123.45
and then parse this into two Strings and a double. Scanner as you mentioned is a good way to start, then try
String[] parts = input.split(" ");
double value = Double.parseDouble(parts[2]);
This will split the input into a String array of size 3 and convert the third element to a double object, that will allow you to create Customers.
For your second question, you can use a simple approach by iterating over all Customers in the ArrayList, and store the current customer with the highest amount. Replacing the customer if you find a bigger spender.
Viku, try moving
arraylist.add(new Customer(name,gender,amountSpent));
to within the
do{
...
arraylist.add(new Customer(name,gender,amountSpent));
} while(choice.equalsIgnoreCase("Yes"));
As the code is now, the arrayList.add is only executed after the loop -> only last entry.
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
I am extremely new to java and am very close to finishing a project I have been trying to finish for a long time. Whenever I try to run the code. It gives a null pointer exception as soon as the constructer is called. My code is listed below and any help would be appreciated.
Main class:
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 register.");
int arraySize = Input.nextInt();
Input.nextLine();
Employee employee = new Employee(arraySize);
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String dateOfHireTemp;
for(int x = 0; x < arraySize; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
employee.addEmployee(x, namesTemp, streetTemp, cityTemp, stateTemp, zipCodeTemp, dateOfHireTemp);
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
}
for(int x = 0; x < arraySize; x++)
{
String info[] = employee.getEmployeeInfo(x);
System.out.println("Employee ID: " + (x + 1));
System.out.println("Name: " + info[0]);
System.out.println("Address: " + info[1]);
System.out.println("Date of Hire: " + info[2]);
}
}
}
Employee class:
public class Employee
{
private EmployeeName name;
private EmployeeAddress address;
private EmployeeDateOfHire hireDate;
public Employee(int arraySize)
{
}
public void addEmployee(int x, String name, String street, String city, String state, String zipCode, String hireDate)
{
this.name.setName(x, name);
this.address.setAddress(x, street, city, state, zipCode);
this.hireDate.addDateOfHire(x, hireDate);
}
public String[] getEmployeeInfo(int x)
{
String info[] = new String[3];
info[0] = name.getName(x);
info[1] = address.getAddress(x);
info[2] = hireDate.getDateOfHire(x);
return info;
}
}
EDIT--
Here is how I wrote my data classes. They are all written in the same format.
Name Class:
public class EmployeeName
{
private String names[];
public void setArray(int x)
{
String array[] = new String[x];
this.names = array;
}
public void setName(int x, String name)
{
this.names[x] = name;
}
public String getName(int x)
{
return this.names[x];
}
}
In the addEmployee() method
public void addEmployee(int x, String name, String street, String city, String state, String zipCode, String hireDate)
this.name.setName(x, name);
this.address.setAddress(x, street, city, state, zipCode);
this.hireDate.addDateOfHire(x, hireDate);
}
you haven't initialized name or the other fields. By default, instance fields will be initialized to null. Trying to dereference null will cause a NullPointerException.
You should initialize those fields, for example in your Constructor
public Employee(int arraySize)
{
this.name = new EmployeeName();
this.address = new EmployeeAddress();
this.hireDate = new EmployeeDateOfHire();
}
I don't know what those classes look like.
Seeing
private String names[];
public void setArray(int x)
{
String array[] = new String[x];
this.names = array;
}
public void setName(int x, String name)
{
this.names[x] = name;
}
You call setName() which would also throw a NullPointerException because you're trying to dereference names but it's null. You would have to call setArray() first but then that would fail too because if x is 0, you will create an array of size 0 but then try to access the element at index 0, which would not exist. If x was 1, you would create array of size 1 but try to access the element at index 1 (second element), which would throw an IndexOutOfBoundsException.
Seriously rethink your design. Why is this EmployeeName class so complicated? Why don't you just have a String field name. Or two fields, firstName and lastName?