Java开发:如何避免计数器变量低于0及equals方法输出优化
Hey there! Let's fix up your Counter class to meet your requirements and address the equals method question.
1. Fixing the Negative Counter Restriction
Right now your setCounter method lets the counter go negative, which violates your requirement. We need to add a check here to reject negative values and show an error message. Here's how to update that method:
public void setCounter(int newCounter){ if (newCounter < 0) { // Print error to standard error stream (more appropriate for error messages) System.err.println("Error: Counter cannot be set to a negative value."); // Leave the counter at its current value instead of updating return; } counter = newCounter; }
This change works seamlessly with your plus1 and minus1 methods since they both call setCounter. For example, if the counter is at 0 and you call minus1(), it will try to set it to -1, trigger the error message, and keep the counter at 0.
2. Outputting Equality Status for Counter Instances
First, a quick note: Java's standard equals method is designed to return a boolean (it's part of the Object class contract), so we shouldn't change its return type to a string. Instead, we have two clean approaches to handle the output:
Option 1: Add a dedicated comparison method (best practice)
Add this method to your Counter class to handle the equality output directly:
public void printEqualityStatus(Counter otherCounter) { if (this.equals(otherCounter)) { System.out.println("The two counter instances are equal."); } else { System.out.println("The two counter instances are not equal."); } }
Also, it's important to override the standard equals(Object) method (instead of overloading it with a Counter parameter) to follow Java conventions. Here's the corrected equals method plus a matching hashCode (required when overriding equals):
@Override public boolean equals(Object obj) { // Check if we're comparing the exact same instance if (this == obj) return true; // Check if the other object is null or a different class if (obj == null || getClass() != obj.getClass()) return false; // Cast to Counter and compare values Counter other = (Counter) obj; return counter == other.counter; } @Override public int hashCode() { // Return a hash code tied to the counter value (matches our equals logic) return Integer.hashCode(counter); }
Option 2: Print the result directly when calling equals (simpler for quick use)
If you don't want to add a new method, you can handle the output in your main code:
Counter counter1 = new Counter(); Counter counter2 = new Counter(); if (counter1.equals(counter2)) { System.out.println("The two counters are equal."); } else { System.out.println("The two counters are not equal."); }
Full Updated Counter Class
Putting it all together, here's the complete corrected class:
public class Counter { private int counter; public Counter() { counter = 0; } // Add 1 to counter public void plus1(){ setCounter(getCounter() + 1); } // Subtract 1 from counter public void minus1(){ setCounter(getCounter() - 1); } // Update counter with negative value validation public void setCounter(int newCounter){ if (newCounter < 0) { System.err.println("Error: Counter cannot be set to a negative value."); return; } counter = newCounter; } // Get current counter value public int getCounter(){ return counter; } @Override public String toString(){ return "The counter is currently at " + counter + "."; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Counter other = (Counter) obj; return counter == other.counter; } @Override public int hashCode() { return Integer.hashCode(counter); } // Method to print equality status between two counters public void printEqualityStatus(Counter otherCounter) { if (this.equals(otherCounter)) { System.out.println("The two counter instances are equal."); } else { System.out.println("The two counter instances are not equal."); } } }
内容的提问来源于stack exchange,提问作者Citadel One

