1

I run the following

Choice choice1 = new Choice(0); Choice choice2 = new Choice(1); int result = choice1.compareWith(choice2); IO.outputln("Actual: " + result); 

the compareWith method

public int compareWith(Choice anotherChoice) { int result=0; if (anotherChoice==0||type==0) result=1; if (anotherChoice==1&&type==1) result=-11; } 

The program said that i can not compare anotherchoice (choice class) with a integer. How can I do it.

1
  • as the error says, anotherchoice is of type Choice. I assume you want to compare instance variable type. So it should be anotherChoice.type == this.type Commented Aug 3, 2017 at 10:30

2 Answers 2

2
if (anotherChoice==0||type==0) 

Since anotherChoice is an object you cannot directly compare with 0. You should actually check a field of that object. So your code should be

if (anotherChoice.type==0|| this.type==0) 

Same for the other condition.

And another error is that you are not returning anything from your method. You should.

public int compareWith(Choice anotherChoice) { int result=0; if (anotherChoice==0||type==0) result=1; if (anotherChoice==1&&type==1) result=-11; return result; } 
Sign up to request clarification or add additional context in comments.

Comments

1

You should be implementing Comparable for this. You should also need to get the type value out of the Choice when you are comparing the values:

public class Choice implements Comparable<Choice> { @Override public int compareTo(Choice that) { int result = 0; if (anotherChoice.type == 0 || type == 0) result = 1; if (anotherChoice.type == 1 && type == 1) result = -11; // should probably be -1 return result; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.