Strange program behaviour - java

This elementary program is driving me up the wall.
There must be something very simple I don't see here.
WHY is the exception triggered?
There are 2 classes:
1)
public class Person
{
private String name;
private int age;
private static int numberOfPeople = 0;
public Person()
{
this("John Doe", 0);
numberOfPeople++;
}
public Person(String name, int age)
{
this.setAge(age);
this.setName(name);
numberOfPeople++;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public int getNumberOfPersons()
{
return numberOfPeople;
}
public String toString()
{
return this.name + " " + this.age;
}
}
2)
import java.util.Random;
public class Adult extends Person
{
private String number;
public static final int MIN_AGE = 18;
public Adult(String name, int age, String number)
{
super(name, 0);
this.setAge(age);
this.number = number;
}
public Adult(Adult adult)
{
this(adult.getName(), adult.getAge(), adult.getNumber());
}
public Adult()
{
this.number = "";
this.setAge(MIN_AGE);
Random rand = new Random();
int result = rand.nextInt(2);
if (result == 0)
{
this.setName("John Doe");
}
else
{
this.setName("Jane Doe");
}
}
public void setAge(int age)
{
if (age < MIN_AGE)
{
throw new IllegalArgumentException("The person must be 18 or older!");
}
else
{
super.setAge(MIN_AGE);
}
}
public String getNumber()
{
return this.number;
}
private void setNumber(String number)
{
this.number = number;
}
public String toString()
{
return this.getName() + " " + this.getNumber() + " " + this.getAge();
}
public boolean equals(Object obj)
{
boolean result = false;
if (obj != null && this.getClass() == obj.getClass())
{
Adult other = (Adult) obj;
if (this.getName().equals(other.getName()) &&
this.getNumber().equals(other.getNumber()) &&
this.getAge() == other.getAge())
{
result = true;
}
}
return result;
}
public static void main(String[] args)
{
Adult ad = new Adult();
System.out.println(ad);
}
}
This gives my the following error:
Exception in thread "main" java.lang.IllegalArgumentException: The person must be 18 or older!
at people.Adult.setAge(Adult.java:39)
at people.Person.<init>(Person.java:16)
at people.Adult.<init>(Adult.java:12)
at people.Adult.main(Adult.java:75)

Your Person() constructor creates another person. Since Adult extends Person, there is an implicit super() call which is likely the cause of your error.

Related

can arguments from a class that has objects passed to it work as a valid class to encapsulate the arguments in a method?

so i need to make a method to Rent a specific car to a specific customer in a specific
date. and that the car won't be rented at the same time more than once. this is what i cam up with. here are the exact words.
ClassRentalCompany (Main operations)
Attributes:
o static list of cars: ArrayList
(multi-aggregation from Car class)
o static list of transactions: ArrayList
(multi-aggregation from RentTransaction class)
static methods:
o Buying a new car and adding it to the application: takes
one argument (Car car): must ensure that the car has not
been added before.
o Renting a specific car to a specific customer in a specific
date: takes three arguments (Car car, Customer
customer, RentDate date): must ensure that the same car
won’t be rented twice in the same day
public boolean carRental(RentTransactions newTransaction) {
boolean carRented = false;
if (!carList.isEmpty()) {
for (RentalCars car : carList) {
//my problem is with the .rentDate.UCI
if (car.rentDate.equals(newTransaction.rentdate) && car.UCI == newTransaction.UCI) {
carRented = true;
break;
}
}
}
return carRented;
}
the .rentDate, UCI(unique customer ID) comes from the passed objects in RentTransactions class. the actual classes for date, car and customer are these classes...
public class DateOfRenting {
private int day;
private int month;
private int year;
public DateOfRenting(){
this(0, 0, 0);
}
public DateOfRenting(int day, int month, int year){
this.day = day;
this.month=month;
this.year=year;
}
public int getday() {
return day;
}
public void setday(int day) {
this.day=day;
}
public int getmonth() {
return month;
}
public void setmonth(int month) {
this.month=month;
}
public int getyear() {
return year;
}
public void setyear(int year) {
this.year=year;
}
#Override
public String toString()
{
return day+"/"+month+"/"+year;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass()){
return false;
}
DateOfRenting other = (DateOfRenting) obj;
return this.day == other.day && this.month == other.month &&
this.year == other.year;
}
}
import java.io.*;
import java.util.*;
public class Customers {
private final int UCI;
private String Name;
private int age;
private String gender;
public Customers(){
this(0, null, 0, null);
}
public Customers(int UCI, String Name, int age, String gender){
this.UCI = UCI;
this.Name=Name;
this.age=age;
this.gender=gender;
}
public int getUCI() {
return UCI;
}
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 getgender() {
return gender;
}
public void setbrandname(String gender) {
this.gender=gender;
}
#Override
public String toString()
{
return "the Unique civil ID is "+UCI+"the customer name is "+Name+
"the age of the customer is "+age+"the gender of the customer is "+
gender;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (!super.equals(obj)) {
return false;
}
Customers other = (Customers) obj;
return Objects.equals(UCI, other.UCI);
}
}
import java.io.*;
import java.util.*;
public class RentalCars implements Comparable<RentalCars> {
private final String UNP;
private String brandName;
private double rental_Rates;
private int wheel_Drive;
private String color;
private int milage;
public RentalCars(){
this(null,null, 0.0, 0, null, 0);
}
public RentalCars(String UNP, String brandName, double rental_Rates, int wheel_Drive,
String color, int milage){
this.UNP = UNP;
this.brandName=brandName;
this.rental_Rates=rental_Rates;
this.wheel_Drive=wheel_Drive;
this.color=color;
this.milage=milage;
}
public String getUNP() {
return UNP;
}
public String getbrandName() {
return brandName;
}
public void setbrandname(String brandName) {
this.brandName=brandName;
}
public double getrental_Rates() {
return rental_Rates;
}
public void setrental_Rates(double rental_Rates) {
this.rental_Rates=rental_Rates;
}
public int getwheel_Drive() {
return wheel_Drive;
}
public void setwheel_Drive(int wheel_Drive) {
this.wheel_Drive=wheel_Drive;
}
public String getcolor() {
return color;
}
public void setcolor(String color) {
this.color=color;
}
public int getmilage() {
return milage;
}
public void setmilage(int milage) {
this.milage=milage;
}
#Override
public String toString()
{
return "the Number Plate of the car is "+UNP+"the Car brand is "+brandName+
"the rent rate of this car is "+rental_Rates+"the wheel drive is "+
wheel_Drive+"the color of the car is "+color+"the milage is "+milage;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (!super.equals(obj)) {
return false;
}
RentalCars other = (RentalCars) obj;
return Objects.equals(UNP, other.UNP);
}
public int compareTo(RentalCars rc){
return UNP.compareTo(rc.UNP);
}
}
and the class RentTransactions is this...
public class RentTransactions {
RentalCars car;
Customers customer;
DateOfRenting rentDate;
public RentTransactions(){
}
public RentTransactions(RentalCars car, Customers customer, DateOfRenting rentDate){
this.car = car;
this.customer=customer;
this.rentDate=rentDate;
}
public RentalCars getcar() {
return car;
}
public void setcar(RentalCars car) {
this.car = car;
}
public Customers getcustomer() {
return customer;
}
public void setcustomer(Customers customer) {
this.customer = customer;
}
public DateOfRenting getrentDate() {
return rentDate;
}
public void setcar(DateOfRenting rentDate) {
this.rentDate = rentDate;
}
#Override
public String toString()
{
return car+"/"+customer+"/"+rentDate;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass()){
return false;
}
RentTransactions other = (RentTransactions) obj;
return this.car == other.car && this.rentDate == other.rentDate;
}
}
while the main operations method is this...
import java.util.*;
public class RentalCompany {
public static final List<RentalCars> carList = new ArrayList<>();
public static final List<RentTransactions> transactionList = new ArrayList<>();
public RentalCompany() {
}
public static List<RentalCars> getCar() {
return carList;
}
public static List<RentTransactions> getTransaction() {
return transactionList;
}
public static void buyCar(RentalCars car) {
carList.add(car);
}
public static void buycarcheck(String UNP) {
carList.stream().filter(car -> (car.getUNP().equals(UNP))).forEachOrdered(car -> {
carList.remove(car);
});
}
public boolean carRental(RentTransactions newTransaction) {
boolean carRented = false;
if (!carList.isEmpty()) {
for (RentalCars car : carList) {
//my problem is with the .rentDate.UCI
if (car.rentDate.equals(newTransaction.rentdate) && car.UCI == newTransaction.UCI) {
carRented = true;
break;
}
}
}
return carRented;
}
}
you say what i tried and what i expected is for the attributes to be passed

stream().filter between Classes

I have 2 classes
Mother and Newborn
Class Mother:
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class Mother extends NewBorn {
private List<NewBorn> newBornList = new ArrayList<>();
private Set<NewBorn> children;
private int id;
private String name;
private int age;
public Mother(Mother mother, List<NewBorn> newBornList, Set<NewBorn> children, int id, String name, int age) {
super(mother);
this.newBornList = newBornList;
this.children = children;
this.id = id;
this.name = name;
this.age = age;
}
public Mother(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public Mother(int id, String gender, String name, int birthdate, int weight, int height, List<NewBorn> newBornList, Set<NewBorn> children, int id1, String name1, int age) {
super(id, gender, name, birthdate, weight, height);
this.newBornList = newBornList;
this.children = children;
this.id = id1;
this.name = name1;
this.age = age;
}
public List<NewBorn> getNewBornList() {
return newBornList;
}
public void setNewBornList(List<NewBorn> newBornList) {
this.newBornList = newBornList;
}
public Set<NewBorn> getChildren() {
return children;
}
public void setChildren(Set<NewBorn> children) {
this.children = children;
}
#Override
public int getId() {
return id;
}
#Override
public void setId(int id) {
this.id = id;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public String toString() {
return "Mother{" +
"newBornList=" + newBornList +
", children=" + children +
", id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
Class NewBorn:
public class NewBorn {
private Mother mother;
public NewBorn(Mother mother) {
this.mother = mother;
}
public NewBorn() {
}
public Mother getMother() {
return mother;
}
public void setMother(Mother mother) {
this.mother = mother;
}
private int id;
private String gender;
private String name;
private int birthdate;
private int weight;
private int height;
private int motherId;
public NewBorn(int id, String gender, String name, int birthdate, int weight, int height) {
this.id = id;
this.gender = gender;
this.name = name;
this.birthdate = birthdate;
this.weight = weight;
this.height = height;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBirthdate() {
return birthdate;
}
public void setBirthdate(int birthdate) {
this.birthdate = birthdate;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getMotherId() {
return motherId;
}
public void setMotherId(int motherId) {
this.motherId = motherId;
}
#Override
public String toString() {
return "NewBorn{" +
"mother=" + mother +
", id=" + id +
", gender='" + gender + '\'' +
", name='" + name + '\'' +
", birthdate=" + birthdate +
", weight=" + weight +
", height=" + height +
", motherId=" + motherId +
'}';
}
}
I have to get the mother older then 25years old that have child more then 4000g weigth
I did the following
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
List<Mother> motherabove = above25YoAndChildHeavierThen4000g(mothers, newBorns);
System.out.println("List with mothers above 25 years old and childs that are over 4000g weigth: " + motherabove + "\n");
}
public static List<Mother> parseMotherFileTxt() throws IOException {
List<Mother> mothers = new ArrayList<>();
BufferedReader bufferedReader = new BufferedReader(new FileReader("src\\mamy.txt"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] s = line.split("\\s");
mothers.add(new Mother(Integer.parseInt(s[0]), s[1], Integer.parseInt(s[2])));
}
bufferedReader.close();
return mothers;
}
public static List<NewBorn> parseNewBornFileTxt() throws IOException {
List<NewBorn> newBorn = new ArrayList<>();
BufferedReader bufferedReader = new BufferedReader(new FileReader("src\\noworodki.txt"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] s = line.split("\\s");
newBorn.add(new NewBorn(Integer.parseInt(s[0]), s[1], s[2], Integer.parseInt(s[4]), Integer.parseInt(s[5]), Integer.parseInt(s[6])));
}
bufferedReader.close();
return newBorn;
}
public static List<Mother> above25YoAndChildHeavierThen4000g(List<Mother> motherList, List<NewBorn> newBornList) {
return motherList.stream()
.filter(mother -> mother.getAge() > 25)//over 25yo
.filter(mother -> mother .getMotherId() == newBorn.getId())//get mother that have same id as child so assuming that means that this is the mother of the child
.filter(newBorn-> newBorn.getWeight() > 4000)//child over 4000g
.collect(Collectors.toList());// I expect to collect all the filters and return the correct output : Example Mother is : 112 Laura 38
and she have a child : 29 s Gabriel 1999-11-16 4100 54 112 = where 112 is the mother id that `I know is child of the mother`
}
I think something is wrong in the relation between the classes because I assume that the filter should work just fine if everything else is ok.
Normally should have mother has a list of children and a specific child has a field mother so with this I should be able to filter through.
I think you are looking for something like:
public static List<Mother> above25YoAndChildHeavierThen4000g(List<Mother> motherList, List<NewBorn> newBornList) {
return motherList.stream()
.filter(mother -> mother.getAge() > 25)
.filter(mother -> mother.getChildren().stream()
.anyMatch(child -> child.getWeight() > 4000))
.collect(Collectors.toList());
}
However the code overall definitely needs cleaning as advised in the comments
public List motherMoreThan() {
List list = new ArrayList<>();
for (Mother mother : mothers) {
if (mother.getAge() > 25 && isChildOver4000(mother)) {
list.add(mother);
}
}
return list;
}
public boolean isChildOver4000(Mother mother) {
for (Newborn newborn : mother.getList()) {
if (newborn.getWeight() > 4000) {
return true;
}
}
return false;
}
you can call them like this :
System.out.println("\nMothers over 25 Years old with childer heavier than 4000g;");
app.motherMoreThan()
.forEach(System.out::println);

Class is not abstract and does not override abstract method problem

I tried hard to make it. But I've got an error message
"Student is not abstract and does not override abstract method compareTo(Object) in Comparable
class Student extends Person {"
abstract class Person implements Comparable {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Student extends Person {
private int id;
public Student(String name, int id) {
super(name);
this.id = id;
}
public String toString() {
return Integer.toString(id);
}
public int getId() {
return this.id;
}
#Override
public int compareTo(Student s) {
if (this.id < s.getId()) {
return -1;
}else if (this.id > s.getId()) {
return 1;
}
return 0;
}
}
#Override
public int compareTo(Student s) {
if (this.id < s.getId()) {
return -1;
}else if (this.id > s.getId()) {
return 1;
}
return 0;
}
this is where I think having a problem...
As already explained by #Andreas, make Student implements Comparable, not Person.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
abstract class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Student extends Person implements Comparable<Student> {
private int id;
public Student(String name, int id) {
super(name);
this.id = id;
}
public String toString() {
return Integer.toString(id);
}
public int getId() {
return this.id;
}
#Override
public int compareTo(Student o) {
return Integer.compare(this.id, o.id);
}
}
Demo
public class Main {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student("Abc", 321));
list.add(new Student("Xyz", 12));
list.add(new Student("Mnp", 123));
Collections.sort(list);
System.out.println(list);
}
}
Output:
[12, 123, 321]

cqengine cant index by equals

I'm trying to add an index where my override equals() determines if two objects are the same or not.
Car.java
public static class Car {
final String id;
private String name;
public Car(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static final Attribute<Car, Car> CAR = new SimpleAttribute<Car, Car>() {
#Override
public Car getValue(Car car, QueryOptions queryOptions) {
return car;
}
};
#Override
public String toString() {
return "Car{" + "id=" + id + ", name=" + name + '}';
}
}
Fetcher.java
public static final ResultSet<Car> get(final IndexedCollection<Car> indexedCollection, final Car car) {
return indexedCollection.retrieve(QueryFactory.equal(Car.CAR, car));
}
Main.java
public static void main(String args[]) {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<>();
cars.addIndex(NavigableIndex.onAttribute(Car.CAR));
}
The problem is on this line cars.addIndex(NavigableIndex.onAttribute(Car.CAR)); where the error message is no suitable method found for onAttribute(Attribute<Car,Car>). Am I doing something wrong here or is there another call I should be using instead?
Remove cars.addIndex(NavigableIndex.onAttribute(Car.CAR));, because it is not really an usefull index... and I think this was not a motivation of the developer. You should create Attributes for CAR_ID and CAR_NAME and create an Query for comparison. In this case I misuse (to achieve what you expect) IndexedCollection as a simple Set. But... here is a possible solution, if I have understood you correctly:
Override equals in Car:
class Car {
private final int id;
private String name;
public Car(int i, String name) {
this.id = i;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null) return false;
if (!(obj instanceof Car)) return false;
Car car = (Car) obj;
if(car.getId() == this.getId())
if(car.getName().equals(this.getName()))
return true;
return false;
}
public static final Attribute<Car, Car> CAR = new SimpleAttribute<Car, Car>() {
#Override
public Car getValue(Car car, QueryOptions queryOptions) {
return car;
}
};
#Override
public String toString() {
return "Car{" + "id=" + id + ", name=" + name + '}';
}
}
Main:
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<>();
cars.add(new Car(1, "test"));
cars.add(new Car(2, "test2"));
cars.add(new Car(3, "test3"));
Car s = new Car(2, "test2");
ResultSet<Car> cs= cars.retrieve(QueryFactory.equal(Car.CAR, s));
cs.forEach(c -> System.out.println(c.toString()));

Reading in file to array and using it to initialize objects

I have 5 classes (they're small). PersonDemo (test class), Person (superclass), and Student, Instructor and Graduate Student (sub classes). All the classes except for PersonDemo are finished.
I need to read in a file (data.txt) and store it to array Person. Then need I need to determine which object to initialize depending on the first value of the array. ( 1 - person, 2 - student, 3 - instructor or 4 - graduate student ) - I'm having trouble with this part.
Can someone point me in the right direction? My classes are below along with what the input file (data.txt) looks like and what the output file should look like.
PersonDemo.Java
public class PersonDemo
{
public static void main ()
{
JFileChooser chooser = new JFileChooser();
Scanner fileScanner = null;
Person [] ins = new Person [10];
try {
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
fileScanner = new Scanner(selectedFile);
while(fileScanner.hasNextLine())
{
// Need to load "data.txt" into array
// Then need I need to determine which object to initialize depending on the
// first value of the array in "data.txt"
//( 1 - person, 2 - student, 3 - instructor or 4 - graduate student )
}
fileScanner.close();
}
}
catch (FileNotFoundException e)
{
System.out.println("Could not find file");
}
}
public static void showAll(Person [] ins)
{
// Future code here
}
}
Person.java (superclass)
public class Person
{
private String name;
private int age;
public Person()
{
name="";
age=0;
}
public Person(String name, int age)
{
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 String toString()
{
return "Name: " + name + "\t" + "Age: " + age;
}
}
Student.java (subclass)
public class Student extends Person
{
private int studentID;
private String major;
public Student()
{
studentID = 0;
major = "";
}
public Student(String name, int age, int studentID, String major)
{
super(name, age);
this.major = major;
this.studentID = studentID;
}
public int getID()
{
return studentID;
}
public void setID(int studentID)
{
this.studentID = studentID;
}
public String getMajor()
{
return major;
}
public void setMajor(String major)
{
this.major = major;
}
public String toString()
{
return super.toString() + "Student ID: " + studentID + "Major: " + major;
}
}
GraduateStudent.java (subclass)
public class GraduateStudent extends Student
{
private String researchArea;
public GraduateStudent()
{
researchArea = "";
}
public GraduateStudent(String name, int age, int studentID, String major, String researchArea)
{
super(name, age, studentID, major);
this.researchArea = researchArea;
}
public String getArea()
{
return researchArea;
}
public void setArea(String researchArea)
{
this.researchArea = researchArea;
}
public String toString()
{
return super.toString() + "Research Area: " + researchArea;
}
}
Instructor.java (subclass)
public class Instructor extends Person
{
private int salary;
public Instructor()
{
salary = 0;
}
public Instructor(String name, int age, int salary)
{
super(name, age);
this.salary = salary;
}
public int getSalary()
{
return salary;
}
public void setSalary(int salary)
{
this.salary = salary;
}
public String toString()
{
return super.toString() + "Salary: " + salary;
}
}

Categories

Resources