Counter: decrease method disregards boolean - java

I am trying to create a counter that holds a number that can be increased and decreased. The program also has a boolean check: when true, the counter cannot go negative. The program seems to run fine, but I cannot get the decrease methods (both decrease by one and decrease by input) to get the boolean right. It does not check the boolean value or something? I am new to Java and need help understanding what is wrong. The class is as follows:
public class Counter {
private int value;
private boolean check;
public Counter(int startingValue, boolean check) {
if (this.check = true) {
this.value = startingValue;
if (value < 0) {
value = 0;
}
}
if (this.check = false) {
this.value = startingValue;
}
}
public Counter(int startingValue) {
this.check = false;
this.value = startingValue;
}
public Counter(boolean check) {
this.check = check;
}
public Counter() {
this.value = 0;
this.check = false;
}
public int value() {
return this.value;
}
public void increase() {
value++;
}
public void decrease() {
if (this.check == true) {
this.value--;
if (value < 0) {
value = 0;
}
} else if (this.check == false) {
this.value--;
}
}
public void increase(int IncreaseAmount) {
if (IncreaseAmount >= 0) {
this.value = value + IncreaseAmount;
}
}
public void decrease(int DecreaseAmount) {
if (DecreaseAmount >= 0) {
this.value = value - DecreaseAmount;
}
if (check == true && value < 0) {
value = 0;
}
}
}
Now, if I was to execute a main program with this class like this for example:
Counter count = new Counter (2, true);
count.decrease();
count.decrease();
count.decrease();
What I want my program to do is to not go negative since the boolean check is true. Yet it does go to -1. Why is this?

You fail to set the global variable check to false. You also used = instead of ==:
use:
public Counter(int startingValue, boolean check) {
this.check = check;
if (check == true) {
value = startingValue;
if (value < 0) {
value = 0;
}
}
else {
value = startingValue;
}
}

You need to use == to compare equality. The use of a single = sets the value.
Better yet, when checking the value of a boolean, just use the boolean. So instead of
if (someBool == true)
prefer
if (someBool)
Similarly, instead of
if (someBool == false)
prefer
if (!someBool)

Your boolean tests in your if statements need to use == for equality comparison in your constructor.
In your constructor's second if statement, you are assigning check to false.

When performing boolean logic with a boolean, just use the boolean.
So instead of
"if (this.check == true)" do "if (this.check)"
and
"if (this.check == false)" do "if (!this.check)"
Also, you had "if (this.check = true)" for some, which assigns true to this.check.
You main issue is that you missed an assignment of an method parameter to the object variable "this.check = check; // I added this"
Compare your version with this:
public class Counter {
private int value;
private boolean check;
public Counter(int startingValue, boolean check) {
this.check = check; // I added this
if (this.check) { //I changed this
this.value = startingValue;
if (value < 0) {
value = 0;
}
} else { //and this
this.value = startingValue;
}
}
public Counter(int startingValue) {
this.check = false;
this.value = startingValue;
}
public Counter(boolean check) {
this.check = check;
}
public Counter() {
this.value = 0;
this.check = false;
}
public int value() { //good practice to use getVar and setVar, ie: getValue()
return this.value;
}
public void increase() {
value++;
}
public void decrease() {
if (this.check) { // you are not consistent with this.value VS value, which can be a confusing practise
this.value--;
if (value < 0) {
value = 0;
}
} else {
this.value--;
}
}
public void increase(int increaseAmount) { //you had "IncreaseAmount", good practice to start vars with lower case
if (increaseAmount >= 0) {
this.value = + increaseAmount;
}
}
public void decrease(int decreaseAmount) {
if (decreaseAmount >= 0) {
this.value = value - decreaseAmount;
}
if (check && (value < 0)) {
value = 0;
}
}
public void print(){
System.out.println("value:"+value+" check:"+check);
}
public static void main(String[] args) {
Counter count = new Counter (2, true);
count.decrease();
count.print();
count.decrease();
count.print();
count.decrease();
count.print();
}
}

Related

Java - TreeMap do not retrieves the key

I've topped with a problem I can not understand exactly what's happening here.
I operate with a TreeMap<Custom_class, TreeMap<Custom_class, Integer>>
Here is the fragment of code:
TreeMap<Coordenada, Integer> helper_tree;
boolean newLine = false;
for (Linea l : this.lineas) {
int helper = 0;
newLine = true;
Coordenada helper_co = null;
for (Coordenada c : l.getNodosLinea()) {
helper++;
if (!c.getEsEstacion() && !c.getEsCruce()) continue;
if (newLine) { map.putIfAbsent(c, new TreeMap<>()); helper_co = c; helper = 0; newLine = false; continue; }
helper_tree = new TreeMap<>();
helper_tree.put(helper_co, helper * 200);
map.put(c, helper_tree);
map.get(helper_co).put(c, helper * 200);
helper_co = c;
helper = 0;
}
}
In the execution the highlighted line fails, getting 0 entry for a key:
debug mode in intellij
And this is TreeMap structure:
TreeMap structure
I dont understand why in fails at .get(key) when the key Coordenada(12,2) is present. All before works just fine.
Coordenada class
public class Coordenada implements Comparable<Coordenada>{
private int[] coordenada = new int[2];
private boolean esEstacion = false;
private boolean esCruce = false;
public Coordenada(int[] coordenada){
this.coordenada[0] = coordenada[0];
this.coordenada[1] = coordenada[1];
}
public void setCoordenada(int[] coordenada) {
this.coordenada = coordenada;
}
public int[] getCoordenada() {
return coordenada;
}
public void switchEstacion(){
this.esEstacion = !this.esEstacion;
}
public void switchCruce() { this.esCruce = !this.esCruce; }
public boolean getEsEstacion() {
return this.esEstacion;
}
public boolean getEsCruce() { return this.esCruce; }
#Override
public boolean equals(Object coord){
Coordenada coordTemp = (Coordenada) coord;
if (this.coordenada[0] != coordTemp.coordenada[0])
return false;
if (this.coordenada[1] != coordTemp.coordenada[1])
return false;
return true;
}
#Override
public int compareTo(Coordenada o) {
if (this.coordenada[0] > o.coordenada[0] )
return 1;
if (this.coordenada[1] > o.coordenada[1] )
return 1;
if (this.coordenada[0] < o.coordenada[0])
return -1;
if (this.coordenada[1] < o.coordenada[1])
return -1;
return 0;
}
#Override
public String toString() {
return "(" + coordenada[0] + ", " + coordenada[1] + ")";
}
}
Inserts perfectly Coordenada(12,2) and modifies previous helper_co = Coordenada(10,2)
debugger variables
Thanks for any help!
Look at your compareTo function
(0,1) compareTo (1,0) returns 1
(1,0) compareTo (0,1) returns 1
It's ambiguous.

Comparator doesn't work with Binary Tree

I have this thing
Comparator.java
public interface Comparator<T> {
public int compareTo(int num);
}
valueComparator.java
public class valueComparator implements Comparator<Tree.Node> {
#Override
public int compareTo(Tree.Node obj, int number) {
if (obj.getDataNumber() == number) {
return 0;
}
else if (obj.getDataNumber() < number) {
return -1;
}
else return 1;
}
}
Tree.java
public class Tree {
public Node root;
Tree() {
}
public static class Node {
Node(int number, String str, boolean flag) {
dataNumber = number;
dataText = str;
dataBool = flag;
}
public int getDataNumber() {
return this.dataNumber;
}
public String getDataText() {
return this.dataText;
}
public boolean getDataBool() {
return this.dataBool;
}
public void setDataText(String text) {
this.dataText = text;
}
public void isDataBool(boolean flag) {
this.dataBool = flag;
}
Node left;
Node right;
private int dataNumber;
private String dataText;
private boolean dataBool;
}
public void binaryTree() {
root = null;
}
public boolean search(int number) {
return search(root, number);
}
valueComparator comp = new valueComparator();
private boolean search(Node node, int number) {
if (node == null) {
return false;
}
if (comp.compareTo(node, number) == 0) {
return true;
}
if (comp.compareTo(node, number) == -1) {
return search(node.left, number);
}
else {
return search(node.right, number);
}
}
public void insertLeaf(int number, String str, boolean flag) {
root = insertLeaf(root, number, str, flag);
}
private Node insertLeaf(Node node, int number, String str, boolean flag) {
if (node == null) {
node = new Node(number, str, flag);
} else {
if (number < node.dataNumber) {
node.left = insertLeaf(node.left, number, str, flag);
}
else if (number > node.dataNumber) {
node.right = insertLeaf(node.right, number, str, flag);
}
else {
System.out.println("The element is already in the tree.");
}
}
return node;
}
}
Test.java
public class Test {
public static void main(String args[]) {
Tree binTree = new Tree();
binTree.binaryTree();
binTree.insertLeaf(5, "text2", true);
binTree.insertLeaf(4, "text4", false);
binTree.insertLeaf(1, "text1", true);
binTree.insertLeaf(3, "text3", true);
binTree.insertLeaf(2, "text5", false);
System.out.println("Element 3 found: " + binTree.search(3));
// Element 3 found: false
}
}
I am supposed to do the search with a comparator, but I fail to understand the logic. The compareTo method works for itself but it stucks at the recursive call of search. After the first pass, if the return of compareTo is not = 0, then it enters with null and breaks out of recursion and returns false. Meaning if I set the first element of the tree to be '3', the search(3) will return true, but if it's different than 3 - false and won't even look for it in the tree.
When you insert a number you compare it directly to the nodes' values and if the number is less than the value stored in the current node, you follow the left pointer.
However when you search for a number, you use a comparator, which compares the node's value to the number given (note the opposite order!) and if the number is less than the value in the current node, you follow a right link.
Use either direct comparision or a comparator, as you wish – but use the same method everywhere.

ArrayList comparison

I have an ArrayList made out of classes objects .The class has several String fields . In some classes
some fields that are the same must be removed from the ArrayList .
The field from the class that I need to check is sorted_participants which is set to be the same in some objects.
This is my Class:
public class Neo4jCompensation {
private String number_of_participants;
private String amount;
private String sorted_participants;
private String unsorted_participants;
private String href_pdf_compensation;
private String signed_by_all;
public Neo4jCompensation() {
this.number_of_participants = "";
this.amount = "";
this.sorted_participants = "";
this.unsorted_participants = "";
this.href_pdf_compensation = "";
this.signed_by_all = "";
}
public String getNumber_of_participants() {
return number_of_participants;
}
public void setNumber_of_participants(String number_of_participants) {
this.number_of_participants = number_of_participants;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getSorted_participants() {
return sorted_participants;
}
public void setSorted_participants(String sorted_participants) {
this.sorted_participants = sorted_participants;
}
public String getUnsorted_participants() {
return unsorted_participants;
}
public void setUnsorted_participants(String unsorted_participants) {
this.unsorted_participants = unsorted_participants;
}
public String getHref_pdf_compensation() {
return href_pdf_compensation;
}
public void setHref_pdf_compensation(String href_pdf_compensation) {
this.href_pdf_compensation = href_pdf_compensation;
}
public String getSigned_by_all() {
return signed_by_all;
}
public void setSigned_by_all(String signed_by_all) {
this.signed_by_all = signed_by_all;
}
}
So I have a first list filled with Classes:
ArrayList<Neo4jCompensation> results_list=new ArrayList<Neo4jCompensation>();
I thought that very good way to find the duplicates is to make a copy of a list , compare the two for the same class fields values and remove the duplicates .
This is how I find the duplicates
ArrayList<Neo4jCompensation> results_list1=new ArrayList<Neo4jCompensation>();
for(Neo4jCompensation pp:results_list)
{
Neo4jCompensation ss=new Neo4jCompensation();
ss.setAmount(pp.getAmount());
ss.setHref_pdf_compensation(pp.getHref_pdf_compensation());
ss.setNumber_of_participants(pp.getNumber_of_participants());
ss.setSigned_by_all(pp.getSigned_by_all());
ss.setSorted_participants(pp.getSorted_participants());
ss.setUnsorted_participants(pp.getUnsorted_participants());
results_list1.add(ss);
}
for (int i = 0; i < results_list.size(); i++) {
Neo4jCompensation kk=new Neo4jCompensation();
kk=results_list.get(i);
for (int j = 0; j < results_list1.size(); j++) {
Neo4jCompensation n2=new Neo4jCompensation();
n2=results_list1.get(j);
if(i!=j)
{
String prvi=kk.getSorted_participants().trim();
String drugi=n2.getSorted_participants().trim();
if(prvi.equals(drugi))
{
// results_list1.remove(j);
out.println("<p> Are equal su :"+i+" i "+j+"</p>");
}
}
}
}
Since I know that I can not loop and remove the elements from the ArrayList at the same
time i tried to use iterators like this ...
int one=0;
int two=0;
Iterator<Neo4jCompensation> it = results_list.iterator();
while (it.hasNext()) {
Neo4jCompensation kk=it.next();
Iterator<Neo4jCompensation> it1 = results_list1.iterator();
while (it1.hasNext()) {
Neo4jCompensation kk1=it1.next();
String oo=kk.getSorted_participants().trim();
String pp=kk1.getSorted_participants().trim();
if(one<two && oo.equals(pp))
{
it1.remove();
}
two++;
}
one++;
}
But it fails and gives me back nothing in ArrayList results_list1 - before removal with iterator it has in it the right elements . How to remove the objects from the array list that have the same field values as some other objects in the ArrayList .
Why not use .removeAll()
results_list1.removeAll(resultList);
This will require you to implement equals and hashcode within Neo4jCompensation
public class Neo4jCompensation {
//Omitted Code
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((number_of_participants == null) ? 0
: number_of_participants.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Neo4jCompensation other = (Neo4jCompensation) obj;
if (number_of_participants == null) {
if (other.number_of_participants != null)
return false;
} else if (!number_of_participants.equals(other.number_of_participants))
return false;
return true;
}
}
Another approach could be:
Overrride equals method in your Neo4jCompensation and check for the sorted_participants and return accordingly. Then use Set as a collection of your objects. Set does not allow duplicates and it uses equals to determine the equality.
for (int i = 0; i < results_list.size(); i++) {
Neo4jCompensation kk=new Neo4jCompensation();
kk=results_list.get(i);
for (int j = 0; j < results_list1.size(); j++) {
Neo4jCompensation n2=new Neo4jCompensation();
n2=results_list1.get(j);
if(results_list1.contains(kk) { results_list1.remove(j); }
}
But you may want to use a Set instead of a List or a data structure that maintains order, like a SortedMap, with a sentinel value.

Having trouble with java class methods

ok so my assignment I'm supposed to write a class that stores a temperature that the user gives and checks it with the set parameters to see if Ethy/Oxygen/Water are either freezing or boiling and then display it at the end which ones will be freezing/boiling at the temperature that they entered. I have the majority of both the class and tester completed but I'm getting several errors on my code. I'm not asking anyone to give me the answer but if you could tell me what I'm doing wrong I would greatly appreciate it. Here is my code for class:
public class FreezingBoilingPoints {
private int temperature;
public FreezingBoilingPoints(int temp) {
temperature = temp;
}
public void setTemperature(int temp) {
temperature = temp;
}
public int getTemperature() {
return temperature;
}
private Boolean isEthylFreezing(int temperature) {
if (temperature <= -173) {
return true;
} else {
return false;
}
}
private Boolean isEthylBoiling(int temperature) {
if (temperature >= 172) {
return true;
} else {
return false;
}
}
private Boolean isOxygenFreezing(int temperature) {
if (temperature <= -362) {
return true;
} else {
return false;
}
}
private Boolean isOxygenBoiling(int temperature) {
if (temperature >= -306) {
return true;
} else {
return false;
}
}
private Boolean isWaterFreezing(int temperature) {
if (temperature <= 32) {
return true;
} else {
return false;
}
}
private Boolean isWaterBoiling(int temperature) {
if (temperature >= 212) {
return true;
} else {
return false;
}
}
public String showTempinfo() {
if (isEthylFreezing()) {
System.out.println("Ethyl will freeze");
}
if (isEthylBoiling()) {
System.out.println("Etheyl will boil");
}
if (isOxygenFreezing()) {
System.out.println("Oxygen will freeze");
}
if (isOxygenBoiling()) {
System.out.println("Oxygen will Boil");
}
if (isWaterFreezing()) {
System.out.println("Water will freeze");
}
if (isWaterBoiling()) {
System.out.println("Water will boil");
}
}
}
and the code for my tester is below:
import java.util.Scanner;
public class FreezingBoilingTester {
public static void main(String[] args) {
int temperature;
FreezingBoilingPoints temp1 = new FreezingBoilingPoints(0);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a temperature: ");
temperature = scan.nextInt();
System.out.println(showTempinfo());
}
}
1) don't pass the temp inside methods, because you already have this value in member variable.
2) you can change if (condition) then true else false into return (condition) and it will be the same result, just for readability .
3) you should return boolean not Boolean wrapper until you need the wrapper.
public final class FreezingBoilingPoints {
private int temperature;
public FreezingBoilingPoints(int temp) {
temperature = temp;
}
public void setTemperature(int temp) {
temperature = temp;
}
public int getTemperature() {
return temperature;
}
private boolean isEthylFreezing() {
return (temperature <= -173);
}
private boolean isEthylBoiling() {
return (temperature >= 172);
}
private boolean isOxygenFreezing() {
return (temperature <= -362);
}
private boolean isOxygenBoiling() {
return (temperature >= -306);
}
private boolean isWaterFreezing() {
return (temperature <= 32) ;
}
private boolean isWaterBoiling() {
return (temperature >= 212);
}
public String showTempinfo() {
StringBuilder result = new StringBuilder();
if (isEthylFreezing()) {
result.append("Ethyl will freeze");
result.append("\n");
}
if (isEthylBoiling()) {
result.append("Etheyl will boil");
result.append("\n");
}
if (isOxygenFreezing()) {
result.append("Oxygen will freeze");
result.append("\n");
}
if (isOxygenBoiling()) {
result.append("Oxygen will Boil");
result.append("\n");
}
if (isWaterFreezing()) {
result.append("Water will freeze");
result.append("\n");
}
if (isWaterBoiling()) {
result.append("Water will boil");
result.append("\n");
}
return result.toString();
}
}
Main:
import java.util.Scanner;
public class FreezingBoilingTester
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a temperature: ");
int temperature = scan.nextInt();
FreezingBoilingPoints temp1 = new FreezingBoilingPoints(temperature );
System.out.println(temp1.showTempinfo());
}
}
updated:
you can use String concatenation:
String result = "";
if ( condition ) {
result += "new result";
result += "\n";
}
but this is not recommended in term of performance, because each += operation will create another String object in memory holding the new result.
The problem is that your private methods are taking in a temperature and yet, you are not passing one in for your showTempinfo() method. Try removing the input parameters and using the temp set in the class. Also, you need to somehow set the temp before you call showTempinfo().
Hope this helps.
You're not passing the input that the user is giving you into the constructor for your FreezingBoilingPoints class. You're initializing that class with 0 and then asking for a temperature from the user. There's no relationship between the temperature the user provided and the class that you're using to test it.
You need to construct your FreezingBoilingPoints object in your main method, then call showTempinfo() on it. Also, your private calc methods should use the member variable; there's no need to take it as a parameter.
You need to pass the user input, temperature, into your FreezingBoilingPoints constructor. Also, the method showTempInfo() is instance specific. For example, you need to instantiate your object, temp1, by passing the user input with the constructor and then invoke temp1.showTempInfo()
Here we go:
1) All your "is..." methods are expecting for an int parameter, however when you're calling them, you're not passing anything. Remove the int parameter from either the method implementation or the method calls
2) You're missing a closing bracket for the method isWaterBoiling;
3) You marked the method "showTempinfo" as returning String, but you are not returning anything for that method. Either add the return command or remove the "String" from the method signature.
In your showTempinfo(), you try to do isEthylFreezing().
But it can't work ... isEthylFreezing is waiting for an int ... but it gets nothing ...

Java Counter Problems

For the public void setValue(int newcount) how do I make it so the value the other program sends is used to set the newcount? Also I have to do this "If the newcount < zero or > maxValue, do nothing."
private int maxValue;
private int count;
/**
* Constructor for objects of class Counter
*/
public Counter(int maxValue)
{
maxValue = 0;
}
public void decrement()
{
if (count == maxValue)
{
count = maxValue;
}
else
{
--count;
}
}
public int getValue()
{
return maxValue;
}
public void increment()
{
if (count == maxValue)
{
count = 0;
}
else
{
++count;
}
}
public void setValue(int newcount)
{
}
public String toString()
{
return "Counter{" + "maxValue=" + maxValue + '}';
}
}
I'm a little confused as to what this does:
public void decrement()
{
if (count == maxValue)
{
count = maxValue;
}
It doesn't seem to actually be decrementing the value. In fact since count == maxValue, there is no point in setting it.
This should work:
public void setValue(int newcount) {
if ((newcount < 0) || (newcount > maxValue))
return;
counter = newcount;
}
Your constructor does not do what you meant it to do:
private int maxValue;
/**
* Constructor for objects of class Counter
*/
public Counter(int maxValue)
{
maxValue = 0;
}
Your code just sets its argument to zero, the argument name hides the attribute (and why set it to 0?)
What would work, adding the #param javadoc line, is:
private int maxValue;
/**
* Constructor for objects of class Counter.
* #param newMaxValue The maximum counter value.
*/
public Counter(int newMaxValue)
{
maxValue = newMaxValue;
}
public void setValue(int newcount)
{
if(newcount >= 0 && newcount <= maxcount)
{
count = newcount;
}
}

Categories

Resources