Taking user input for the objects - java

Question : Create a two objects of class Employee and check both are same or diffrent
Below code gives an error : Exception in thread "main" java.util.InputMismatchException
Only object e1 accepts values
class Employee {
String name;
int age;
char gender;
public Employee() {
super();
}
public Employee (String name, int age, char gender) {
this.gender = gender;
this.name = name;
this.age = age;
}
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 char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
}
public class Source {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Employee e1 = new Employee();
//e1.name = sc.nextLine();
//e1.age = sc.nextInt();
//e1.gender = sc.next().charAt(0);
System.out.println(e1.name+" "+e1.age+" "+e1.gender);
Employee e2 = new Employee();
//e2.name = sc.nextLine();
//e2.age = sc.nextInt();
//e2.gender = sc.next().charAt(0);
System.out.println(e2.name+" "+e2.age+" "+e2.gender);
boolean isSame = e1.equals(e2);
if(e1.equals(e2)) {
System.out.println("Same");
}
else {
System.out.println("Different");
}
}
}
How to take user input or input from keyboard for objects e1 and e2?

I have made some changes to your Employee and Source classes, take a look.
public class Source {
Scanner sc = null;
public static void main(String[] args) {
Source source = new Source();
Employee e1 = source.getEmployee();
Employee e2 = source.getEmployee();
if(e1.equals(e2)) {
System.out.println("Same");
}
else {
System.out.println("Different");
}
source.closeScanner();
}
public Source() {
sc = new Scanner(System.in);
}
public void closeScanner() {
sc.close();
}
public Employee getEmployee() {
Employee e = new Employee();
System.out.print("Enter Name: ");
e.name = sc.next();
System.out.print("Enter Age: ");
e.age = sc.nextInt();
System.out.print("Enter Gender: ");
e.gender = sc.next().charAt(0);
System.out.println(e.getName() + " " + e.getAge() + " " + e.getGender());
return e;
}
}
public class Employee {
String name;
int age;
char gender;
public Employee() {
super();
int age = -1;
}
public Employee (String name, int age, char gender) {
this.gender = gender;
this.name = name;
this.age = age;
}
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 char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + gender;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (age != other.age)
return false;
if (gender != other.gender)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Please note that I've added the following two methods
public int hashCode()
and
public boolean equals(Object obj)
to make it possible to compare the two instances of the employee object

Related

Find max value from an object [duplicate]

This question already has answers here:
Getting max value from an arraylist of objects?
(5 answers)
Closed 2 years ago.
I have super class Person that extends to 2 sup classes (Employee and Student), after I enter the Employee info such as (name, SSN, salary, Gendr) I want to find the Employee with the Max salary and type his\her info, but I don't know how to do that with objects !, if u may please give me a hint I'll be thankfull.
public abstract class Person {
private String name=" ";
private String gender=" ";
private long SSN;
public Person() {
}
public Person(String name, String gender, long SSN) {
this.name = name;
this.gender = gender;
this.SSN = SSN;
}
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;
}
public long getSSN() {
return SSN;
}
public void setSSN(long SSN) {
this.SSN = SSN;
}
#Override
public String toString() {
return name + " " + gender + " " + SSN+ " ";
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if (this.SSN != other.SSN) {
return false;
}
if (!Objects.equals(this.gender, other.gender)) {
return false;
}
return true;
}
}
public class Employee extends Person {
private String type = " ";
private double salary;
public Employee() {
}
public Employee(double salary, String name, String gender, long SSN) {
super(name, gender, SSN);
this.salary = salary;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return super.toString()+ " " + type + " " + salary ;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Employee other = (Employee) obj;
if (Double.doubleToLongBits(this.salary) != Double.doubleToLongBits(other.salary)) {
return false;
}
if (!Objects.equals(this.type, other.type)) {
return false;
}
return true;
}
}
public class Test {
static void print(Person[] all, int count){
System.out.println("The allPersons array contains: ");
for (int i = 0; i <count; i++) {
System.out.println(all[i]);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Person[] allPersons = new Person[5];
String name = " ";
long ssn=0;
String gender = " ";
int count = 0;
boolean s = true;
while(s){
System.out.println("Choose 1 to insert a new student");
System.out.println("Choose 2 to insert new employee");
System.out.println("Choose 3 to retrieve the maximum salary");
System.out.println("Choose 4 to retrieve all software engineering students");
System.out.println("Choose 0 to exit");
System.out.println("Please enter your choice: ");
int n = input.nextInt();
switch(n){
case 1:{ if(count == 5){System.out.println("Sorry, you reach the maximum length."); break;}
Student student = new Student();
System.out.println("Please enter Name: ");
name=input.next();
input.nextLine();
student.setName(name);
System.out.println("Please enter SSN: ");
ssn = input.nextLong();
student.setSSN(ssn);
System.out.println("Plase enter Gender: " );
gender = input.next();
student.setGender(gender);
System.out.println("Please enter major: ");
String major = input.next();
input.nextLine();
student.setMajor(major);
System.out.println("Plase inter Year of Regestration: ");
int year = input.nextInt();
student.setYearOfReg(year);
System.out.println("Please enter Studend ID: ");
long ID = input.nextLong();
student.setID(ID);
allPersons[count]=student;
count++;
print(allPersons,count);}
case 2 :{if (count==5) {System.out.println("Sorry, you reach the maximum length"); break;}
Employee emp = new Employee();
System.out.println("Please enter Name:");
name=input.next();
input.nextLine();
emp.setName(name);
System.out.println("Plese enter SSN:");
ssn=input.nextLong();
emp.setSSN(ssn);
System.out.println("Please enter Gender:");
gender=input.next();
emp.setGender(gender);
System.out.println("Plese enter type: ");
String type = input.next();
input.nextLine();
emp.setType(type);
System.out.println("Please enter Salary:");
double salary = input.nextDouble();
emp.setSalary(salary);
allPersons[count]=emp;
count++;
print(allPersons,count);
}
case 3: //Employee with max salary
case 0: System.out.println("Exit");s=false;break;
}
}
}
}
You can loop over the array of people and find the employee with the highest salary.
Employee highest = null;
for(int i = 0; i < count; i++){
if(allPersons[i] instanceof Employee && (highest == null || ((Employee) allPersons[i]).getSalary() > highest.getSalary())){
highest = (Employee) allPersons[i];
}
}
System.out.println(highest);
You can use a lambda function to obtain the max salary and check the type of person in the same function.
public Employee getMaxSalary(Person[] allPersons) {
return Arrays.asList(allPersons)
.stream()
.filter(Employee.class::isInstance) //Filter only the person who are Employee
.map(Employee.class::cast)
.max(Comparator.comparing(Employee::getSalary)) //Obtain only the max salary
.orElseThrow(NoSuchElementException::new);
}

Testing (if..Else if...Else) statement (not working)

Testing an if else statement that does not seem to be working
Assuming it has something to do with possibly changing the IF else to the getter instead of setter?
or something to do with the variable returning an INT instead of string?
little confused been rearranging and modifying this code for a while now and cant get it to work
//package Driver2;
import java.util.Scanner;
class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;
//Constructors
public Person(String name, String address, String number, int customerPurchase){
this.name = name;
this.address = address;
this.number = number;
this.customerPurchase = customerPurchase;
}
public Person(){}
//Accessors
public String getName(){
return this.name;
}
public String getAddress(){
return this.address;
}
public String getNumber(){
return this.number;
}
public int getcustomerPurchase(){
return this.customerPurchase;
}
//Mutators
public void setName(String n){
this.name = n;
}
public void setAddress(String a){
this.address = a;
}
public void setNumber(String n){
this.number = n;
}
public void setcustomerPurchase(int a){
this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
r = this.customerPurchase;
if (r > 500)
{
System.out.print("5%");
}
else if (r >= 1000)
{
System.out.print("6%");
}
else if (r >= 1500)
{
System.out.print("7%");
}
else if (r >= 2000)
{
System.out.print("10%");
}
else
{
System.out.print("");
}
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private int customerDiscount;
//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
super(name, address, number, customerPurchase);
this.customerNumber = customerN;
this.recieveMail = rm;
}
public Customer(){}
//Accessors
public String getCustomerNumber(){
return this.customerNumber;
}
public boolean getRecieveMail(){
return this.recieveMail;
}
public int getcustomerDiscount()
{
return customerDiscount;
}
//Mutators
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
//private int customerPurchase = 0;
//Constructors
/* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
super();
this.customerPurchase = customerPurchase;
//this.customerDiscount = customerDiscount;
}*/
public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
//super(name, address, number, customerPurchase, customerN, rm);
//this.customerPurchase = customerN;
//this.customerDiscount = pc;
}
public Driver1()
{}
//Accessors
/*
public int getcustomerDiscount()
{
return this.customerDiscount;
}
/*
#Override
public int getcustomerPurchase()
{
return this.customerPurchase;
}
//Mutators
#Override
public void setcustomerPurchase(int c)
{
this.customerPurchase = c;
}*/
/*
public void setcustomerDiscount(int r)
{
this.customerPurchase = r;
if (r >= 500)
{
System.out.print("5%");
}
else if (r >= 1000)
{
System.out.print("6%");
}
else if (r >= 1500)
{
System.out.print("7%");
}
else if (r >= 2000)
{
System.out.print("10%");
}
else
{
System.out.print("");
}
}
*/
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Main
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name of customer:");
String name1 = scanner.nextLine();
System.out.print("Enter address of customer:");
String address1 = scanner.nextLine();
System.out.print("Enter phone number of customer:");
String number1 = scanner.nextLine();
System.out.print("Enter customer number:");
String customerNumber = scanner.nextLine();
System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
String answer = scanner.nextLine();
boolean recieveMail = (answer.equals("yes"));
System.out.print("Enter amount customer has spent:");
int customerPurchase = scanner.nextInt();
Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);
System.out.println("\nCustomer: ");
System.out.println("Name: "+customer.getName());
System.out.println("Address: "+customer.getAddress());
System.out.println("Phone Number: "+customer.getNumber());
System.out.println("Customer Number: "+customer.getCustomerNumber());
System.out.println("Recieve Mail?: "+customer.getRecieveMail());
System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
System.out.println("Percent off: "+customer.getcustomerDiscount());
}
}
The code you have pasted require some changes actually.Assuming you need to return the discount percentage based on the customer input you need to do the following changes.
1) You have a setCustomerDiscount in Person class but the entity you are dealing here is of Customer type so you need to add the setCustomerDiscount in the Customer class instead of Person class.
2) As you want to show the percentage in String(as per your sysout statements/ you can also change to Int as required) you need to change the return type to String instead of Int.
3) Another thing is your order of the if/else if conditions should be in descending order.
Once you fix them, you can get your output as expected.
Below I have made those changes:
import java.util.Scanner;
class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;
//Constructors
public Person(String name, String address, String number, int customerPurchase){
this.name = name;
this.address = address;
this.number = number;
this.customerPurchase = customerPurchase;
}
public Person(){}
//Accessors
public String getName(){
return this.name;
}
public String getAddress(){
return this.address;
}
public String getNumber(){
return this.number;
}
public int getcustomerPurchase(){
return this.customerPurchase;
}
//Mutators
public void setName(String n){
this.name = n;
}
public void setAddress(String a){
this.address = a;
}
public void setNumber(String n){
this.number = n;
}
public void setcustomerPurchase(int a){
this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private String customerDiscount;
//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
super(name, address, number, customerPurchase);
this.customerNumber = customerN;
this.recieveMail = rm;
}
public Customer(){}
//Accessors
public String getCustomerNumber(){
return this.customerNumber;
}
public boolean getRecieveMail(){
return this.recieveMail;
}
public String getcustomerDiscount()
{
return customerDiscount;
}
//Mutators
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
public void setcustomerDiscount(int r)
{
String customerDiscount = "";
if (r >= 2000)
{
customerDiscount="10%";
System.out.print("10%");
}
else if (r >= 1500)
{
customerDiscount="7%";
System.out.print("7%");
}
else if (r >= 1000)
{
customerDiscount="6%";
System.out.print("6%");
}
else if (r > 500)
{
customerDiscount="5%";
System.out.print("5%");
}
else
{
System.out.print("");
}
this.customerDiscount = customerDiscount;
}
}
public class TestMain
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name of customer:");
String name1 = scanner.nextLine();
System.out.print("Enter address of customer:");
String address1 = scanner.nextLine();
System.out.print("Enter phone number of customer:");
String number1 = scanner.nextLine();
System.out.print("Enter customer number:");
String customerNumber = scanner.nextLine();
System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
String answer = scanner.nextLine();
boolean recieveMail = (answer.equals("yes"));
System.out.print("Enter amount customer has spent:");
int customerPurchase = scanner.nextInt();
scanner.close();
Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);
System.out.println("\nCustomer: ");
System.out.println("Name: "+customer.getName());
System.out.println("Address: "+customer.getAddress());
System.out.println("Phone Number: "+customer.getNumber());
System.out.println("Customer Number: "+customer.getCustomerNumber());
System.out.println("Recieve Mail?: "+customer.getRecieveMail());
System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
customer.setcustomerDiscount(customerPurchase);
System.out.println("Percent off: "+ customer.getcustomerDiscount());
}
}
Hope it helps...
I think it is a logical problem. Simply order the discount formula in reverse.
Catch the big numbers first:
if r >= 2000 print 10%
else if r >= 1500 print 7%
else if r >= 1000 print 6%
else if r >= 500 print 5%
else print nothing
I hope that helps you

how to add two objects?

I have two classes:-
public class Employee {
private String name;
private String DOB;
private String techicalSkill;
Employee(){
}
Employee(String name, String DOB, String techicalSkill){
this.name=name;
this.DOB=DOB;
this.techicalSkill=techicalSkill;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDOB() {
return DOB;
}
public void setDOB(String dOB) {
DOB = dOB;
}
public String getTechicalSkill() {
return techicalSkill;
}
public void setTechicalSkill(String techicalSkill) {
this.techicalSkill = techicalSkill;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((DOB == null) ? 0 : DOB.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((techicalSkill == null) ? 0 : techicalSkill.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (DOB == null) {
if (other.DOB != null)
return false;
} else if (!DOB.equals(other.DOB))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (techicalSkill == null) {
if (other.techicalSkill != null)
return false;
} else if (!techicalSkill.equals(other.techicalSkill))
return false;
return true;
}
#Override
public String toString() {
return "Employee [name=" + name + ", DOB=" + DOB + ", techicalSkill=" + techicalSkill + "]";
}
}
and
package learning;
public class Person {
private String address;
private int age;
private int weight;
Person(){
}
public Person(String address, int age, int weight) {
super();
this.address = address;
this.age = age;
this.weight = weight;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + age;
result = prime * result + weight;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (age != other.age)
return false;
if (weight != other.weight)
return false;
return true;
}
#Override
public String toString() {
return "Person [address=" + address + ", age=" + age + ", weight=" + weight + "]";
}
}
Now i have created a main class inside which the details are present:-
import java.util.ArrayList;
public class Main {
Employee e1 = new Employee();
Person p1 = new Person();
public static void main(String[] args) {
ArrayList<Employee> arraylist = new ArrayList<>();
arraylist.add(new Employee("Somduti", "31-08-1992", "Java"));
arraylist.add(new Employee("abc", "30-01-1995", "Android"));
arraylist.add(new Employee("xyz", "24-12-1988", "DotNet"));
arraylist.add(new Employee("Sanj", "01-10-1986", "IOS"));
arraylist.add(new Employee("Pink", "19-07-1991", "ETL"));
System.out.println(arraylist);
ArrayList<Person> arraylist1 = new ArrayList<>();
arraylist1.add(new Person("India", 27, 57));
arraylist1.add(new Person("US", 22, 64));
arraylist1.add(new Person("Australia", 31, 69));
arraylist1.add(new Person("France", 33, 77));
arraylist1.add(new Person("Germany", 28, 55));
System.out.println(arraylist1);
}
}
I want to add the two Objects and print the result as below:-
name=Somduti, DOB=31-08-1992, techicalSkill=Java address=India, age=27, weight=57
How do I that?
I think what you want to achieve is a relation between employees and persons. There are various ways to do that. Here are two common solutions:
Association: Add a person-field to the employee class. This looks like: "private Person person;" within the employee class.
Inheritance: An employee is a specific type of person, so you can let employee "extend" the person class. This looks like: public class Employee extends Person ...
Both ways have advantages and disadvantages. For example: Inheritance is a strong relationship, that you might want in this case. Association is a weaker type of relation, so that you could "replace" the person information of an employee (which might not be want you want).
Add the below additional field in the Employee class as follows:
public class Employee {
private String name;
private String DOB;
private String techicalSkill;
private Person person; // Additional field
Employee() {
}
/**
* #param name
* #param dOB
* #param techicalSkill
* #param person
*/
public Employee(final String name, final String dOB, final String techicalSkill, final Person person) {
super();
this.name = name;
this.DOB = dOB;
this.techicalSkill = techicalSkill;
this.person = person; //additional argument in Constructor
}
}
P.S: No changes to the Person class
Test Main:
Person person = new Person("India", 27, 57);
Employee employee = new Employee("Somduti", "31-08-1992", "Java", person);
System.out.println("name= " + employee.getName() + ", DOB= " + employee.getDOB() + ",techicalSkill= " +
employee.getTechicalSkill() + " address= " + employee.getPerson().getAddress() + ", age= " +
employee.getPerson().getAge() + " weight= " + employee.getPerson().getWeight());
Output:
name= Somduti, DOB= 31-08-1992,techicalSkill= Java address= India, age= 27 weight= 57

Exception in thread "main" java.Lang.NullPointerException; unable to identify problem [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Since I've finished my code I am debugging every step in the main. I keep hitting a NullPointerException not even 40 lines in. The problem is my setter is not working in my Person class. Or what I assume that my setter isn't working. But I also first believe my read isn't working for my file.
I've tried to change around the variables but I simply can't find the problem and why it won't add the name to the Person class. I read into NullPointerExceptions on here and can't find where that problem is for me to fix in my code.
public class Person {
private String firstName;
private String lastName;
private String address;
private String city;
private String state;
private String zipCode;
public Person(String firstName, String lastName, String address, String city, String state, String zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.state = state;
this.zipCode = zipCode;
}
protected Person() {
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
#Override
public String toString() {
return "FirstName: " + firstName + "\nLastName: " + lastName + "\nAddress: " + address + "\nCity: " + city + "\nState: " + state + "\nZipCode: " + zipCode;
}
public String toCSV() {
return this.firstName + "," + this.lastName + "," + this.address + "," + this.city
+ "," + this.state + "," + this.zipCode;
}
public void copy(Person p) {
firstName = p.firstName;
lastName = p.lastName;
address = p.address;
city = p.city;
state = p.state;
zipCode = p.zipCode;
}
public void copy(String firstName, String lastName, String address, String city, String state, String zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.zipCode = zipCode;
}
#Override
public Person clone() {
Person p = new Person(this.firstName, this.lastName, this.address, this.city, this.state, this.zipCode);
return p;
}
}
public class Customer extends Person{
private int customerID;
private double grossSales;
public Customer(int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super(firstName, lastName, address, city, state, zipCode);
this.customerID = customerID;
this.grossSales = grossSales;
}
public Customer(String s, int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super(firstName, lastName, address, city, state, zipCode);
copyCSV(s);
}
protected Customer() {
}
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public double getGrossSales() {
return grossSales;
}
public void setGrossSales(double grossSales) {
this.grossSales = grossSales;
}
#Override
public String toString() {
return "CustomerID: " + customerID + "\nGrossSales: " + grossSales + super.toString();
}
public String toCSV() {
return this.customerID + "," + this.grossSales + "," + super.toCSV();
}
public void copy(Customer c) {
super.copy(c);
customerID = c.customerID;
grossSales = c.grossSales;
}
public void copy(int customerId, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super.copy(firstName, lastName, address, city, state, zipCode);
this.customerID = customerId;
this.grossSales = grossSales;
}
public Customer clone() {
Customer c = new Customer(this.customerID, this.grossSales, this.getFirstName(), this.getLastName(), this.getAddress(), this.getCity(), this.getState(), this.getZipCode());
return c;
}
public int compareTo(Customer c) {
int returnValue = 0;
if (this.customerID > c.customerID) {
returnValue = -1;
} else if (this.customerID < c.customerID) {
returnValue = 1;
} else {
returnValue = 0;
}
return returnValue;
}
public void copyCSV(String s) {
List<String> list = new ArrayList<>();
String[] a = s.split(",");
list = Arrays.asList(a);
this.copy(Integer.parseInt(list.get(0)), Double.parseDouble(list.get(1)), list.get(2),
list.get(3), list.get(4), list.get(5), list.get(6), list.get(7));
}
}
public class CustomerList {
public Customer[] cl;
public int size;
public CustomerList() {
this.cl = new Customer[4];
}
public int size() {
return this.size = cl.length;
}
public Customer get(Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
}
return cl[i];
}
public boolean set(Customer c,Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
} else {
cl[i] = c;
return true;
}
}
public void add(Customer c) {
for (int i = 0; i < size; i++) {
if (cl[i] == null) {
cl[i] = c;
} else {
if (i == size) {
Customer[] temp = new Customer[size * 2];
for (int j = 0; j < size; j++) {
temp[j] = cl[j];
}
cl[size] = c;
size++;
}
}
}
}
public Customer remove(Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
}
Customer temp = cl[i];
for (int j = 0; j < cl.length - 1; j++) {
cl[i] = cl[i + 1];
}
return temp;
}
#Override
public String toString() {
String s = " ";
double sum = 0;
for(Customer c: cl){
if(c == null)
s = "";
else
s += c + " \n";
}
for(Customer c: cl){
if (c == null)
sum += 0;
else
sum += c.getGrossSales();
}
return s + "\n" + "Total Gross Sales = " + Double.toString(sum);
}
public static CustomerList read(String fn) throws FileNotFoundException {
Scanner input = new Scanner(new File(fn));
CustomerList ab = new CustomerList();
try {
while(input.hasNextLine()) {
String currentline = input.nextLine();
Customer cd = new Customer();
cd.copyCSV(currentline);
cd.toCSV();
ab.add(cd);
}
} finally {
return ab;
}
}
//Write is facing the same problems as read. We can't access the toCSV() method from Customer.
public static boolean write(CustomerList cl, String fn) throws FileNotFoundException {
boolean a = false;
PrintWriter output = new PrintWriter(new File(fn));
// try {
for (int i = 0; i < cl.size; i++) {
Customer cd = new Customer();
cd.toCSV();
// }
// } catch (FileNotFoundException s) {
// System.out.println("File does not exist please try again: ");
// return a;
} return a = true;
}
//I utilized the sort function it said to and assume this will work as expected.
public void sort() {
Arrays.sort(cl);
}
public int indexOf(int id) {
for (int i = 0; i < size; i++) {
if(cl[i].getCustomerID() == id) {
return i;
}
}
return -1;
}
public boolean update(int id, double amt) {
boolean test;
int index = indexOf(id);
if(index == -1) {
System.out.println("CustomerID not present");
test = false;
} else {
amt += cl[index].getGrossSales();
test = true;
}
return test;
}
}
public static void main(String[] args) throws FileNotFoundException {
boolean b = false;
// Read file
System.out.println("Read file");
CustomerList cl = CustomerList.read("Customers.csv");
if(cl != null) {
System.out.println("Read: " + cl.size() + " records");
System.out.println(cl.toString() + "\n\n\n");
} else {
System.out.println("File read error.");
return;
}
// Test get and set for CustomerList
System.out.println("Test get and set for CustomerList");
System.out.println("x = " + cl.get(0));
Customer c = cl.get(0);
c.setFirstName("Homer"); // This is the line it keeps stopping at.
cl.set(c, 0);
System.out.println("x = " + cl.get(0));
System.out.println("\n\n\n");
It should be setting the first name of the customer as "Homer"
The only results it prints out is
Read file
Read: 4 records
Total Gross Sales = 0.0
Test get and set for CustomerList
x = null
--- Exception in thread "main" java.lang.NullPointerException
It's pretty simple, you ask to print cl.get(0). it returns null then you say Customer c = cl.get(0) which is null then you try to do c.setFirstName but c is null so nullPointerException.
Your are trying to access c but c is null. you need to initialize it as a new customer or make it equal to an actual customer (not null) before being able to setFirstName. Just do :
Customer c = new Customer();
c.setFirstName("homer");
It would work if your cl was not empty. To avoid this type of error you could also do :
Customer c;
if (cl.get(0) != null){
c = cl.get(0)
} else {
c = new Customer();
}
c.setFirstName("homer");

Created add() method to insert objects into an array and all i get are null values

this is a class called Doglist to add the object to an array.
public class DogList {
private int numItems;
private DogItem[] dogListArray;
private int position;
DogList () {
numItems=0;
position = 0;
dogListArray = new DogItem[10];
}
public void add (DogItem item) {
dogListArray[numItems++]= new DogItem(item.getName(),
item.getBreed(),
item.getWeight(),
item.getOwner1(),
item.getOwner2()
);
}
public String toString() {
String result = "";
for (int i=0; i<numItems; i++) {
result += dogListArray[i].toString() + "\n";
}
return result;
}
public DogItem searchForDogItem (DogItem gi) {
System.out.println("Here is your obj value: " + gi );
return null;
}//This is the one im having trouble with.
}
I have all the setters and getters in the DogItem class.
and this is from the UI where i get the dog info(name, breed, weight, owners1&2 names)
public void searchForItem (String name ) {
DogItem gi = new DogItem (name);
gi = gl.searchForDogItem(gi);
if (gi==null) {
msgTextField.setText("Dog Not Found");
} else {
nameTextField.setText(String.valueOf(gi.getName()));
breedTextField.setText(String.valueOf(gi.getBreed()));
weightTextField.setText(String.valueOf(gi.getWeight()));
owner1TextField.setText(String.valueOf(gi.getOwner1()));
owner2TextField.setText(String.valueOf(gi.getOwner2()));
}
}
Ill try and clear things up as i go.
this is the output i get
Here is your obj value: null null 0.0 null null
Ok so here is what it probably should look like instead. Just from what I saw wrong already. However you'd probably want to override the toString() method of DogItem.
Main method example of this:
public class Main {
public static void main(String[] args) {
DogItem dogItem = new DogItem("Spot", "Dalmation", "45", "Bob", "Sandy");
DogItem.add(dogItem);
DogItem result = DogItem.searchForItem("Spot");
if (result == null) {
System.out.println("Dog not found");
// GUI error output goes here
} else {
System.out.println("Here is your obj value: " + result);
// Where your GUI stuff goes
}
}
}
DogItem example of this:
public class DogItem {
private static DogItem[] dogListArray = new DogItem[100];
private static int numItems = 0;
private String name;
private String breed;
private String weight;
private String owner1;
private String owner2;
public DogItem(String name, String breed, String weight, String owner1, String owner2) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owner1 = owner1;
this.owner2 = owner2;
}
public static void add(DogItem dogItem) {
dogListArray[numItems++] = dogItem;
}
public static DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogListArray) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
#Override
public String toString() {
String result = name + ", " + breed + ", " + weight + ", " + owner1 + " " + owner2;
return result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getOwner1() {
return owner1;
}
public void setOwner1(String owner1) {
this.owner1 = owner1;
}
public String getOwner2() {
return owner2;
}
public void setOwner2(String owner2) {
this.owner2 = owner2;
}
}
These would be recommended changes from me though:
private static ArrayList<String> owners;
private static ArrayList<DogItem> dogsList;
public DogItem(String name, String breed, String weight, String owner) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owners.add(owner);
}
public void init() {
owners = new ArrayList<String>();
dogsList = new ArrayList<DogItem>();
}
public void addDog(DogItem dogItem) {
dogsList.add(dogItem);
}
public DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogsList) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
public void addOwner(String owner) {
owners.add(owner);
}
public String getOwner() {
return owners.get(owners.size() - 1);
}

Categories