Using a method after casting in Java - java

I have written the code:
public int compareTo(Object w) {
//w = (Word)w
if(this.count > (Word) w.getCount()) {
return -1;
} else if (this.count < (Word) w.getCount()) {
return 1;
} else {
return 0;
}
}
I have written the class Word. It implements Comparable so I must use the Object parameter for the compareTo() method.
However, I need the object to use a method in the Word class. I get an error if I cast and was wondering if I am doing something wrong or if I need to try something else?
Word class:
package comp10152_lab3;
public class Word implements Comparable{
private int count;
private String word;
public Word(String word) {
this.word = word;
this.count = 1;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
#Override
public int compareTo(Object w) {
if(this.count > w.getCount()){
return -1;
}
else if (this.count < w.getCount()) {
return 1;
}
else {
return 0;
}
}
public void countUp() {
count++;
}
#Override
public String toString() {
return word + "(" + count + ")";
}
#Override
public boolean equals(Object w) {
return w.equals(word);
}
}
The equals class is suppose to be that way, as per instruction.
The error I am getting is on the w.getCount() which is a "missing symbol" error.

This is the code that you need:
public int compareTo(Object o) {
Word w = (Word) o;
if(this.count > w.getCount()){
return -1;
}
else if (this.count < w.getCount()) {
return 1;
}
else {
return 0;
}
}
The problem that you were having was due to the fact that w was of the type Object, the statement w = (Word) w would not do what you wanted. The second part of the problem has to do with the precedence of the cast operator in Java. When you do (Word)w.getCount(), the getCount() part gets evaluated first, meaning that you were effectively doing (Word) <some int>. What you could have done was wrap it in parentheses like ((Word) w).getCount() to solve that problem.

You should implement Comparable<Word> so that the compareTo method is public int compareTo(Word w). Also you can simplify your compareTo code:
public class Word implements Comparable<Word> {
private int count;
public int compareTo(Word w) {
return w.count - this.count;
}
}
If you can't use java generics then you can still do your compareTo in one line:
public int compareTo(Object w) {
return ((Word) w).count - this.count;
}

Related

How can I compare two strings and return the lexicographical ordered result using the compareTo method?

I am trying to use compareTo method to compare two different names. After running the first attempt the program terminates immediately without returning anything. How can I modify this compareTo method to compare the names (Name n and Name n2) and return the result (-1, 1 or 0)? And obviously a print statement can be added to display (equal, before , or after) for the comparison. Thanks for any assistance.
//First attempt
public class Name implements Comparable<Name> {
private String Name;
public Name(String string) {
// TODO Auto-generated constructor stub
}
public String getName() {
return Name;
}
public int compareTo(Name other) {
if (getName().compareTo(other.getName()) < 0) {
return -1;
} else if (getName().compareTo(other.getName()) > 0) {
return 1;
} else if (getName().equals(other.getName())) {
return 0;
}
return getName().compareTo(other.getName());
}
public static void main(String[] args) {
Name n = new Name("jennifer");
n.getName();
Name n2 = new Name("paul");
n2.getName();
}
}
//second attempt
public class Name implements Comparable<String> {
private String Name;
public String getName() {
return Name;
}
public int compareTo(String other) {
if (getName().compareTo(other.getName()) < 0) {
return -1;
} else if (getName().compareTo(other.getName()) > 0) {
return 1;
} else if (getName().equals(other.getName())) {
return 0;
}
return getName().compareTo(other.getName());
}
public static void main(String[] args) {
String Name = new String("jennifer");
String other = new String("paul");
}
}
//First attempt
public class Name {
public static void main(String[] args) {
String n = new String("jennifer");
String n2 = new String("paul");
if (n.compareTo(n2) < 0) {
System.out.println(n +" is before than " +n2);
} else if (n.compareTo(n2) > 0) {
System.out.println(n +" is after than " +n2);
} else if (n.compareTo(n2) == 0) {
System.out.println(n +" is equals to " +n);
}
}
}
Outoput:
jennifer is before than paul
By the way, check this out because every programming language has its own set of rules and conventions and for variables in Java is like this:
If the name you choose consists of only one word, spell that word in
all lowercase letters. If it consists of more than one word,
capitalize the first letter of each subsequent word.
public class Name implements Comparable<Name> {
private String name;
public Name(String name) {
this.name=name;
}
public String getName() {
return name;
}
public int compareTo(Name other) {
if (getName().compareTo(other.getName()) < 0) {
return -1;
} else if (getName().compareTo(other.getName()) > 0) {
return 1;
} else if (getName().equals(other.getName())) {
return 0;
}
return getName().compareTo(other.getName());
}
public static void main(String[] args) {
Name n = new Name("jennifer");
n.getName();
Name n2 = new Name("paul");
n2.getName();
System.out.println(n.getName());
System.out.println(n2.getName());
System.out.println(n2.compareTo(n));
}
}
OUTPUT :
jennifer
paul
1

Sorting Custom class in java using Comparable

I've got this custom class and I want to sort it by saturation and brightness.
I've tried a custom comperator class, but it doesn't work.
Now I've tried to implement Comparable. The program runs through the code but doesn't sort the list at the end.
Here is my code.
Part of the testing class:
ArrayList<HSBColor> colorList = new ArrayList<HSBColor>(colors.values());
Collections.sort(colorList);
for(HSBColor co : colorList){
System.out.println(co.toString());
}
Custom Class HSBColor
public class HSBColor implements Comparable<HSBColor>{
private float H;
private float S;
private float B;
public HSBColor(float h, float s, float b) {
H = h;
S = s;
B = b;
}
public float getH() {
return H;
}
#Override
public String toString() {
return String.format("%.2f %.2f %.2f", H,S,B);
}
public void setH(float h) {
H = h;
}
public float getS() {
return S;
}
public void setS(float s) {
S = s;
}
public float getB() {
return B;
}
public void setB(float b) {
B = b;
}
#Override
public int compareTo(HSBColor o) {
if(this.getS() > o.getS() && this.getB() > o.getB()){
return 1;
}
else{
return -1;
}
}
}
Thanks in advance!
EDIT: Extra code
This are the colors before the sort:
Color HSB H:28.60465 S:71.07438 B:47.45098
Color HSB H:4.4999995 S:73.059364 B:85.882355 >> This is the one i need
Color HSB H:64.18605 S:79.62963 B:21.176472
Color HSB H:65.714294 S:39.873417 B:61.960785
Color HSB H:23.333332 S:40.0 B:70.588234
This are the colors after the sort
28,60 71,07 47,45
65,71 39,87 61,96
23,33 40,00 70,59
4,50 73,06 85,88
64,19 79,63 21,18
**EDIT new Algorithm **
This one compares it right, but doesn't sort them right..
#Override
public int compareTo(HSBColor o) {
if(this.getS() > o.getS()) {
if(this.getB() >o.getB()){
return 1;
}
else{
return 0;
}
}
else{
if(this.getB() < o.getB()){
return -1;
}
else{
return 0;
}
}
}
Your compareTo method doesn't define a proper ordering.
Suppose that this.getS() > o.getS() but this.getB() < o.getB().
this.compareTo(o) would return -1, but o.compareTo(this) would also return -1.
If A < B and B < A this is not a proper ordering.
A proper ordering would first compare by the more important property, and then, in case of equality, by the less important property.
For example :
#Override
public int compareTo(HSBColor o) {
if(this.getS() > o.getS()){
return 1;
} else if (this.getS() < o.getS()) {
return -1;
} else {
if (this.getB() > o.getB()) {
return 1;
} else if (this.getB() < o.getB()) {
return -1;
} else {
return 0;
}
}
}
There is an issue around compareTo method. You should use it like:
#Override
public int compareTo(HSBColor o) {//if saturation is equal then compare brightness.
if (this.S == o.getS()) {
return Float.compare(B, o.getB());
}
return Float.compare(S, o.getS());
}

Why is class, interface, or enum expected?

How and why am I getting the compiler error ("class, interface, or enum expected")? Here is the code:
public class RolloverCounter{
private int counter=0;
private int max;
public RolloverCounter(int a){
if(a<0){
max = a;
}
}
public void increment()
{
for(int i=0;i<=max;i++)
{
counter++;
System.out.println(counter);
if(counter==max){
counter=0;
}
}
}
public void decrement(){
for(int i=0;i<=max;i++)
counter--;
if(counter<0)
{
counter=max;
}
System.out.println(counter);
}
public String toString() {
return counter;
}
public void reset(){
counter = 0;
}
}
}
What have I done wrong?
Your toString() method isn't returning a String,
public String toString() {
return counter;
}
should be something like
public String toString() {
return String.valueOf(counter);
}
Finally, you appear to have an extra closing brace (at the end) in your code as posted.

Compare an Arraylist and give output

I have two ArrayLists. How can I compare the elements in the arraylists and create a new list with the results?
I need to iterate through the list to actually get its results and compare. How can I do it in Java?
Any help is appreciated.
Thanks
You can compare by implementing Comparator class.You can understand by below example in which Two Time class is getting compared.
class Time
{
int hours,minutes,seconds;
public Time(int hours,int minutes,int seconds)
{
this.hours=hours;
this.minutes=minutes;
this.seconds=seconds;
}
public int getHours()
{
return this.hours;
}
public int getMinutes()
{
return this.minutes;
}
public int getSeconds()
{
return this.seconds;
}
public String toString()
{
return String.format("%d:%02d:%02d %s",((hours==0||hours==12)? 12:hours%12),this.minutes,this.seconds,((hours>=12)?"PM":"AM"));
}
}
class TimeComparator implements Comparator<Time>
{
public int compare(Time t1,Time t2)
{
int hours=t1.getHours()-t2.getHours();
int minutes=t1.getMinutes()-t2.getMinutes();
int seconds=t1.getSeconds()-t2.getSeconds();
if(hours>0)
return 1;
else if(hours<0)
return -1;
if(minutes>0)
return 1;
else if(minutes<0)
return -1;
if(seconds>0)
return 1;
else if(seconds<0)
return -1;
return 0;
}
public boolean equals(Object obj)
{
return true;
}
}
After this you can use Collections class to use any method like sorting or search.
I hope that the following chunck of code will get you started.
import java.util.ArrayList;
class Compare {
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
a.add("Hello");
a.add("Goodbye");
ArrayList<String> b = new ArrayList<String>();
b.add("Hello");
b.add("Bye");
if (a.size() != b.size()) {
System.out.println("Arrays must have the same size");
return;
}
ArrayList<Boolean> results = new ArrayList<Boolean>();
for(int i = 0; i < a.size(); ++i)
results.add(a.get(i).equals(b.get(i)));
for(int i = 0; i < a.size(); ++i)
System.out.println(results.get(i));
}
}

comparing two different data types with compareTo method

I have a a class WordCount that implements Set, but I'm having trouble using the comareTo method in WordCount class who get the method from the Word class. I'm trying to compare Word object to String object, but in the end Word is a String also, so why is it giving me errors?
Word class
public class Word implements Comparable<String>{
String word;
int count;
public Word(String s)
{
word = s;
count = 1;
}
#Override
public int compareTo(String o) {
return word.compareTo(o);
}
#Override
public String toString()
{
return word + "(" + count + ")";
}
}
I'm having error in this class when using the compareTo method
public class WordCount implements Set<Word>{
private Word[] items;
private int size;
public WordCount()
{
items = new Word[5];
size = 1;
}
#Override
public void add(Word s)
{
int i = 0;
//grow array as needed
if (size >= items.length) {
items = grow(items);
}
while (i < size) {
if (items[i].compareTo(s) > 0) {
break;
}
if (items[i].equals(s)) {
return;
}
i++;
}
items[i] = s;
size++;
}
#Override
public void show()
{
for(Word s : items)
{
System.out.println(s);
}
}
public Word[] grow(Word[] a) {
Word[] newA = new Word[a.length + 5];
System.arraycopy(a, 0, newA, 0, a.length);
return newA;
}
}
Declare your Word class as Comparable<Word>. (As #Louis Wasserman commented, almost always, a class is Comparable to itself or a superclass)
then
#Override
public int compareTo(Word o) {
return word.compareTo(o.word);
}
Also, consider getting rid of Word altogether, and instead use a Map<String, Integer> where the key is the word you are counting, and the value is the count.
The compareTo method in your Word class is expecting a string parameter, but you're passing it a Word instance when you call it in your WordCount class. Your Word class doesn't extend the String class, so you have a mismatched type error.

Categories

Resources