Im trying to make a comparison operator that checks if the content of 2 objects are the same, in this instance the Object is called Game and has atributes releaseJaar and naam.
The first call of the method .equals() works just fine but when i try to call it a second time it says it cant resolve the method?
public boolean equals(Object andereObject){
if (andereObject instanceof Game) {
if (((Game) andereObject).getNaam().equals(naam) && ((Game) andereObject).getReleaseJaar().equals(releaseJaar)){
return true;
}
}
else {
return false;
}
}
I dont know what i'm doing wrong here :(
Ps: might be multiple things since i just started on the subject of 1 to many relations.
public class Game {
private String naam;
private int releaseJaar;
private double nieuwprijs;
private int ditJaar = LocalDate.now().getYear();
public Game(String nm, int rJ, double nwpr){
this.naam = nm;
this.releaseJaar = rJ;
this.nieuwprijs = nwpr;
}
public String getNaam(){
return naam;
}
public double getReleaseJaar(){
return releaseJaar;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public double huidigeWaarde(){
int jaarVerschil = ditJaar - releaseJaar;
double nieuweWaarde = nieuwprijs;
for (int i = 0; i < jaarVerschil; i++){
nieuweWaarde = nieuweWaarde * 0.7;
}
return nieuweWaarde;
}
//De werkende functie moet nog gemaakt worden
public boolean equals(Object andereObject){
if (andereObject instanceof Game) {
if (((Game) andereObject).getNaam().equals(naam) && ((Game) andereObject).getReleaseJaar().equals()){
return true;
}
}
else {
return false;
}
}
#Override
public String toString() {
return "Game{" +
"naam='" + naam + '\'' +
", releaseJaar=" + releaseJaar +
", nieuwprijs=" + nieuwprijs +
'}';
}
}
Related
I'm very new to Java and I keep getting this error and I can't figure it out.
Error: Could not find or load main class
restaurantclient.RestaurantClient
Java Result: 1
This is on Netbeans and I'm sure I've done everything right. This is for my homework for a Java class and I would really appreciate your help. I have been working on this problem for days now.
import java.text.DecimalFormat;
public class RestaurantClient {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Restaurant r1;
Restaurant r2;
r1 = new Restaurant("PizzaHut", 152, (float) 4.95); //instantiating
r2 = new Restaurant("Dominos", 10, (float) 3.657);
System.out.print(r1.toString());
System.out.print(r2.toString());
r2.setPeopleServed(r1.getPeopleServed());
r2.setAveragePrice(r1.getAverageMeal());
if (r1.equals(r2)) //checking if equal
System.out.println("\nThe two objects are the same");
else
System.out.println("\nThe two objects are NOT the same");
r2.setName(r1.getName());
if (r1.equals(r2)) //checking if equal
System.out.println("\nThe two objects are the same");
else
System.out.println("\nThe two objects are NOT the same");
DecimalFormat pricePattern = new DecimalFormat("$###,###,000.00");
System.out.println("Tax paid per year: " + pricePattern.format(r1.averageTaxes()));
}
}
//Restaurant.java
public class Restaurant extends Store {
private int peopleServed;
private float avgmeal;
public Restaurant(String newName, int peopleServed, float avgmeal) {
super(newName);
setPeopleServed(peopleServed);
setAveragePrice(avgmeal);
}
public void setPeopleServed(int newpeopleServed) {
if (newpeopleServed >= 0)
peopleServed = newpeopleServed; //mutator alows client to change the value of name
else
System.out.println("Number has to be greater than zero");
}
public void setAveragePrice(float newprice) {
if (newprice >= 0)
avgmeal = newprice; //mutator alows client to change the value of name
else
System.out.println("Number has to be greater than zero");
}
public int getPeopleServed() {
return peopleServed; //accessor; returns current value
}
public float getAverageMeal() {
return avgmeal; //accessor; returns current value
}
public String toString() {
return "Name of store is: " + super.getName() +
"\nNumber of people served is " + peopleServed +
"\nAverage price per person is " + avgmeal + "\n";
}
public boolean equals(Object o) {
if (!(o instanceof Restaurant))
return false;
else {
Restaurant objRest = (Restaurant) o;
if (avgmeal == objRest.avgmeal && peopleServed == objRest.peopleServed && super.equals(objRest))
return true;
else
return false;
}
}
public double averageTaxes() {
double avgtaxes = (double)(super.taxrate * (peopleServed * avgmeal * 365));
return avgtaxes; //accessor; returns current value
}
}
//Store.java
public class Store {
private String storename;
public final float taxrate = (float) .08000;
public Store(String newName) //constructor
{
setName(newName);
}
public String getName() {
return storename; //accessor; returns current value
}
public void setName(String newName) {
storename = newName; //mutator alows client to change the value of name
}
public String toString() {
return "Name of store is: " + storename;
}
public boolean equals(Object o) {
if (!(o instanceof Store))
return false;
else {
Store objStore = (Store) o;
if (storename.equals(objStore.storename))
return true;
else
return false;
}
}
}
The system is looking for a main class restaurantclient.RestaurantClient, so a class RestaurantClient in package restaurantClient, but your class RestaurantClient seems to be in the default package.
try this if you are not getting any compilation issues.
You can :
RightClick on project node and go to Set configuration.
Select the main class for your application.
Then clean and build.
Even if the above steps don't work for you then then delete the Netbeans cache by deleting the (index) folder
Fore more details
Follow the stackOverflow question
Netbeans - Error: Could not find or load main class
I've created this method and I'm unsure why it says there's a missing return statement. do I need to change the print to a return? (it's the method at the very bottom) I'm a bit of a Java beginner so any help will be appreciated!
public class Book {
private String title;
private String author;
private int copies;
private boolean borrowed;
public Book( String inAuthor, String inTitle, int inNumberOfCopies ) {
this.author = inAuthor;
this.title = inAuthor;
this.copies = inNumberOfCopies;
}
public void borrowed() {
borrowed = true;
}
public void rented() {
borrowed = true;
}
public void returned() {
borrowed = false;
}
public boolean isBorrowed() {
return borrowed;
}
public String getAuthor() {
return this.author;
}
public static String getTitle() {
return getTitle();
}
public int getTotalCopies() {
return this.copies;
}
public int getAvailableCopies() {
}
public void withdrawCopy() {
int found = 0;
for (Book b : Library.getListOfBooks()) {
if (b.getTitle().equals(title)) {
if (found == 0) {
found = 1;
}
if (!b.isBorrowed()) {
b.borrowed=true;
found = 2;
break;
}
if (found == 0) {
System.out.println("Sorry, this book is not in our catalog.");
} else if (found == 1) {
System.out.println("Sorry, this book is already borrowed.");
} else if (found == 2) {
System.out.println("You successfully borrowed " + title);
}
}
}
}
public String returnCopy() {
boolean found = false;
for (Book book : Library.getListOfBooks()) {
if (getTitle().equals(title) && book.isBorrowed()) {
book.returned();
found = true;
}
if (found) {
System.out.println("you successfully returned " + title);
}
}
}
}
public String returnCopy()
String after public means that this method will return a String.
Your public String returnCopy() is currently not returning anything.
If you don't want to return anything, you can use void like this:
public void returnCopy(){
// code
}
Same issue with public int getAvailableCopies(), this is supposed to return an int but you are not returning anything.
Be careful:
this method:
public static String getTitle() {
return getTitle();
}
is a recursive method without a base condition. This will cause an error and force your application to crash.
You've defined the method as returning a String but you don't return a value anywhere in the method body. Simplest fix is probably to change the return type to void...
public void returnCopy() {...
}
All the above answer are pointing to the same issue, you have defined methods that are breaking the contract about what they return..
In you code you have as well something like this:
public int getAvailableCopies() {
}
so you are telling the compiler, you have a method with the name getAvailableCopies, it takes no params and return an integer.
BUT if you don't return anything, then you are contradicting your own method, your own contract, this is an enough reason for a compiler to complain...
Conclusion:
keep in mind the information that defines the method.
I have three integer values along with its text. My requirement is to give rank to all of them.
E.g. I have A = 50 points, B = 500 Points, C = 50 points.
Now I would like to compare all of these and find max and equal values and its according name(like, A/B/C).
EDIT ::
As a output it should return, B = 1st Rank, A = 2nd Rank, C = 2nd Rank.
If anyone has any idea about how can I implement code as per my requirement then, it would be great.
Thanks in advance.
public class ScoreVO implements Comparator<Integer> {
private String playerName = Constants.BLANK_STRING;
private int playerScore;
public String getPlayerName () {
return playerName;
}
public void setPlayerName ( String playerName ) {
this.playerName = playerName;
}
public int getPlayerScore () {
return playerScore;
}
public void setPlayerScore ( int playerScore ) {
this.playerScore = playerScore;
}
#Override
public int compare ( Integer o1, Integer o2 ) {
return o2.compareTo ( o1 );
}
}
Here is my class with Comparator<>.
Please suggest me if I am wrong.
A sample running code which gives output shown below as per your requirement along with player rank. There is a separate method assignRank(List<>) which you can use to assign ranks to players.
Score List: [ScoreVO [playerName=B, playerScore=500, playerRank=1], ScoreVO [playerName=A, playerScore=50, playerRank=2], ScoreVO [playerName=C, playerScore=50, playerRank=2]]
public class ScoreExample {
public static void main(String[] args) {
List<ScoreVO> scoreList = new ArrayList<ScoreVO>();
scoreList.add(new ScoreVO("A", 50));
scoreList.add(new ScoreVO("C", 50));
scoreList.add(new ScoreVO("B", 500));
Collections.sort(scoreList);
assignRank(scoreList);
System.out.println("Score List: "+scoreList);
}
private static void assignRank(List<ScoreVO> scoreList) {
int rank = 0;
int score = 0;
for(ScoreVO scoreVO : scoreList) {
if(score != scoreVO.getPlayerScore()) {
rank++;
scoreVO.setPlayerRank(rank);
score = scoreVO.getPlayerScore();
} else {
scoreVO.setPlayerRank(rank);
}
}
}
}
class ScoreVO implements Comparable<ScoreVO> {
public String playerName;
public int playerScore;
public int playerRank;
public ScoreVO(String playerName, int playerScore) {
this.playerName = playerName;
this.playerScore = playerScore;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public int getPlayerScore() {
return playerScore;
}
public void setPlayerScore(int playerScore) {
this.playerScore = playerScore;
}
public int getPlayerRank() {
return playerRank;
}
public void setPlayerRank(int playerRank) {
this.playerRank = playerRank;
}
#Override
public int compareTo(ScoreVO o) {
if(o.getPlayerScore() != getPlayerScore()) {
if(getPlayerScore() > o.getPlayerScore())
return -1;
else
return 1;
}
return getPlayerName().compareTo(o.getPlayerName());
}
#Override
public String toString() {
return "ScoreVO [playerName=" + playerName + ", playerScore="
+ playerScore + ", playerRank=" + playerRank + "]";
}
}
ScoreVO should implement Comparable<ScoreVO>. And your compareTo method looks like this:
#Override
public int compareTo ( ScoreVO o ) {
if(playerScore != o.playerScore)
return Integer.compare(playerScore, o.playerScore);
return playerName.compareTo(o.playerName);
}
You should implment Comparable for ordering purpuses, and equals() for equation (that can use compareTo)
like this
public class ScoreVO implements Comparable<ScoreVO> {
#Override
public int compareTo(ScoreVO other) {
return other == null ? 1 : getPlayerScore() - other.getPlayerScore();
}
#Override
public boolean equals(object other) {
return !(other instanceof ScoreVO) ? false : compareTo(other) == 0 ;
}
}
However, you probably want to compare equality based on player name. think of putting ScoreVO object in a map - what is the key? so -
#Override
public boolean equals(object other) {
return other == null || !(other instanceof ScoreVO) ? false :
getPlayerName.equals(other.getPlayerName()) ;
}
As there are just three values, it is possible to hard-code all operations. You can think of a very compact and efficient way to work this out.
Every comparison of two values can give an outcome >, = or <. Assigning the value 0, 1 or 2 to these, you can pack the three comparisons in a single number using base 3 encoding. You will end up with a number in range 0 to 26, and every different value corresponds to a different answer that you can tabulate (or process in a switch statement).
int Compare(int A, int B) { return A > B ? 0 : (A == B ? 1 : 2); }
char* Answer[27]= { "A1B2C3", "A1B1C3", "B1A2C3", ... }; // To be filled
return Answer[Compare(A, B) + 3 * compare(B, C) + 9 * compare(A, C)];
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Hey guys I just had a question about toString. On a previous test my professor had this overrided method for toString that was similar to this method which I'm testing:
public String toString()
{
String s="";
s+="units: " + units;
s+="\n";
s+="owner: " +owner;
return s;
}
This method is is inside the class Residential which inherits from a base class Construction. Anyways, this mirrors a problem I had on a test where I would try to do say:
Residential R1 = new Residential();
R1.toString();
I thought R1.toString(); would display, which I put on the test, but obviously it was marked wrong and it doesn't.
So now I'm going over the problem and how to correct it. I tried doing say:
System.out.println(R1.toString());
but it's still giving me some weird output like "Residential#5c538b31". Why does it not overriden?
edit: The whole residential class, I'm aware it's not overridden, now but it wasn't annoted with a #Override by the professor in his code either so I assumed it wasn't needed.
public class Residential extends Construction {
private int units;
private String owner;
Residential ()
{
super();
units = 0;
owner = "Unknown";
}
Residential (String n, int y, double a, int u, String o)
{
super (n,y,a);
units = u;
owner = o;
}
public int getUnits()
{
return units;
}
public void setUnits(int u)
{
units = u;
}
public String getOwner()
{
return owner;
}
public void setOwner(String o)
{
owner = o;
}
public void display()
{
System.out.println("Name: " + getName() + " Year: " + getYear() + " Area: " + getArea() + " Number of Units: " + getUnits() + " Owner: " + getOwner());
}
public boolean isEqual (Residential r)
{
if (this.getName() == r.getName() && this.getYear() == r.getYear() && this.getArea() == r.getArea() && this.units == r.units && this.owner == r.owner)
{
return true;
}
return false;
}
public String toString()
{
String s="";
s += "the units is: " + units;
s += "\n";
s += "Owner: " + owner;
return s;
}
edit 2: Added construction class
public class Construction {
private String buildername;
private int year;
private double area;
Construction()
{
buildername = "Unknown";
year = 0;
area = -1;
}
Construction(String b, int y, double a)
{
buildername = b;
year = y;
area = a;
}
//Mutators
public void setName(String n)
{
buildername = n;
}
public void setYear(int y)
{
year = y;
}
public void setArea (double a)
{
area = a;
}
//Accessors
public String getName()
{
return buildername;
}
public int getYear()
{
return year;
}
public double getArea()
{
return area;
}
public void display()
{
System.out.println("Builder's Name: " + getName() + " Year: " + getYear() + " Area: " + getArea());
}
public boolean isEqual(Construction c)
{
if (this.buildername == c.buildername && this.year == c.year && this.area == c.area)
{
return true;
}
return false;
}
}
but it's still giving me some weird output like "Residential#5c538b31". What am I doing wrong?
This means that your version of the Residential class does not correctly override the toString() method.
To fix this, you need to give your class a proper toString override. I would also give the method an #Override annotation to be sure that it's truly overriding the method.
You also state:
On a previous test my professor had this overrided method for toString that was similar to this method which I'm testing...
... and yet you have not shown us the method that you're "testing". Perhaps you want to do this.
Edit
Regarding your posted code, that code is not what has produced the output that you've posted. Perhaps you need to refresh or restart your IDE, but the output could not possibly come from the posted code.
As an aside, your Residential toString() method should also call its parent class's toString() method in its method body, since the String returned should be part of Residential's String.
Im trying to sort my planes by Ascending and Descending order. I have a hashmap of planes and i want to compare them so that i can get the next plane due and last plane due by sorting the map by timeLimitBeforeLand. I wrote a compareTo method which looks like :
//---------------------------------------------------------------------------------------
// CompareTo() used with the Comparable implementation.
//---------------------------------------------------------------------------------------
public int compareTo(Object arg0)
{
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.timeLimitBeforeLand - p.getLimitBeforeLand());
}
return 0;
}
CompareTo takes timeLimitBeforeLand:
// ---------------------------------------------------------------------------------------
// Name: getTimeLimitBeforeLand.
// Description: Get the time before every plane is going to land.
//---------------------------------------------------------------------------------------
public double getTimeLimitBeforeLand()
{
double fuelConsumption;
double timeLimitBeforeLand = 0;
for (TreeMap<String, Plane> theEntry : airlineMap.values()) {
for (Plane aPlane : theEntry.values()) {
if (aPlane.getPlaneType() == aPlane.getPlaneType().AIRBUS) {
System.out.println(" ");
System.out.println(aPlane);
fuelConsumption = 2;
timeLimitBeforeLand = (double) (aPlane.getFuelRemaining() / fuelConsumption);
System.out.println(timeLimitBeforeLand + " minutes to land.");
System.out.println(" ");
} else if (aPlane.getPlaneType() == aPlane.getPlaneType().CORPORATE) {
System.out.println(" ");
System.out.println(aPlane);
fuelConsumption = 3;
timeLimitBeforeLand = (aPlane.getFuelRemaining() / fuelConsumption);
System.out.println(timeLimitBeforeLand + " minutes to land.");
System.out.println(" ");
} else if (aPlane.getPlaneType() == aPlane.getPlaneType().PRIVATE) {
System.out.println(" ");
System.out.println(aPlane);
fuelConsumption = 4;
timeLimitBeforeLand = (double) (aPlane.getFuelRemaining() / fuelConsumption);
System.out.println(timeLimitBeforeLand + " minutes to land.");
System.out.println(" ");
}
}
}
return timeLimitBeforeLand;
}
My attempt so far in the mainApp:
TreeMap<String, PlaneStore> map = new TreeMap<String, PlaneStore>();
ArrayList<Plane> copyList = new ArrayList<Plane>(map.);
Plane comp = new Plane();
Collections.sort(copyList, plane);
Plane Class:
//---------------------------------------------------------------------------------------
// Name: Imports.
// Description: To allow the use of different Java classes.
//---------------------------------------------------------------------------------------
import java.io.Serializable;
//---------------------------------------------------------------------------------------
//Name: Class declaration.
//---------------------------------------------------------------------------------------
public class Plane implements Comparable, Serializable
{
//---------------------------------------------------------------------------------------
// Variable declarations.
//---------------------------------------------------------------------------------------
private String flightNumber;
public String airlineName;
private double fuelRemaining;
private int overdue;
private int passengerNumber;
//---------------------------------------------------------------------------------------
// Enum declaration.
//---------------------------------------------------------------------------------------
private AIRPLANETYPE planeType;
private boolean isLanded = false;
public double timeLimitBeforeLand;
//---------------------------------------------------------------------------------------
// Enum Constuctor.
//---------------------------------------------------------------------------------------
public enum AIRPLANETYPE
{
AIRBUS("1"), CORPORATE("2"), PRIVATE("3");
private String planeName;
private AIRPLANETYPE(String planeName)
{
this.planeName = planeName;
}
public String getPlaneName()
{
return this.planeName;
}
}
//---------------------------------------------------------------------------------------
// Constructor.
//---------------------------------------------------------------------------------------
public Plane(String flightNumber, String airlineName,
double fuelRemaining, int overdue, int passengerNumber,
AIRPLANETYPE planeType, boolean isLanded)
{
this.flightNumber = flightNumber;
this.airlineName = airlineName;
this.fuelRemaining = fuelRemaining;
this.passengerNumber = passengerNumber;
this.overdue = overdue;
this.planeType = planeType;
this.isLanded = isLanded;
}
//---------------------------------------------------------------------------------------
// Getters and Setters.
//---------------------------------------------------------------------------------------
public String getAirlineName()
{
return airlineName;
}
public void setAirlineName(String airlineName)
{
this.airlineName = airlineName;
}
public void setOverdue(int overdue)
{
this.overdue = overdue;
}
public int getOverdue()
{
return overdue;
}
public String getFlightNumber()
{
return flightNumber;
}
public void setFlightNumber(String flightNumber)
{
this.flightNumber = flightNumber;
}
public double getFuelRemaining()
{
return fuelRemaining;
}
public void setFuelRemaining(double fuelRemaining)
{
this.fuelRemaining = fuelRemaining;
}
public int getPassengerNumber()
{
return passengerNumber;
}
public void setPassengerNumber(int passengerNumber)
{
this.passengerNumber = passengerNumber;
}
public AIRPLANETYPE getPlaneType()
{
return planeType;
}
public void setPlaneType(AIRPLANETYPE planeType)
{
this.planeType = planeType;
}
public boolean isLanded()
{
return isLanded;
}
public void setLanded(boolean isLanded)
{
this.isLanded = isLanded;
}
public double getLimitBeforeLand()
{
return timeLimitBeforeLand;
}
public void setTimeLimitBeforeLand(double timeLimitBeforeLand)
{
this.timeLimitBeforeLand = timeLimitBeforeLand;
}
//---------------------------------------------------------------------------------------
// CompareTo() used with the Comparable implementation.
//---------------------------------------------------------------------------------------
public int compareTo(Object arg0)
{
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.timeLimitBeforeLand - p.getLimitBeforeLand());
}
return 0;
}
//---------------------------------------------------------------------------------------
// toString().
//---------------------------------------------------------------------------------------
public String toString()
{
return "Plane: flightNumber=" + flightNumber + "."
+ " airlineName=" + airlineName + "."
+ " fuelRemaining=" + fuelRemaining + " litres."
+ " overdue=" + overdue + " minutes."
+ " passengerNumber="+ passengerNumber + "."
+ " airplaneType=" + planeType +
"hasLanded=" + isLanded+ ".\n";
}
}
The second argument in Collections.sort is for a Comparator not a Plane. Since I saw no mention of a Comparator, you should be able to use the natural order (defined by the compareTo method in your Plane object) and not have a second argument in the Collections.sort
EDIT: Unless you have just excluded that code, you aren't creating any Plane instances and you're using empty collections here...
TreeMap<String, PlaneStore> map = new TreeMap<String, PlaneStore>();
ArrayList<Plane> copyList = new ArrayList<Plane>(map.);
and you will be sorting by PlaneStores so you have to obtain all the Planes in each PlaneStore and add them to your copyList before sorting.
I would consider researching each of the Collections a little more and deciding what the best one for your need would be.