1. Make the following changes to the given Calculator class. i. The add method s
ID: 3668043 • Letter: 1
Question
1. Make the following changes to the given Calculator class.
i. The add method should add the parameter to the total variable
ii. The subtract method should subtract the parameter from the total variable
iii. The getTotal method should return the correct total
iv. The multiply method should multiply the total by the total by the parameter
v. The divide method should divide the total by the parameter. Use integer division. If the parameter is zero, set the total to zero. Do not print an error message.
vi. The getHistory method should NOT be changed at this time and should continue to return an empty String
2. Make the changes to the Calculator class as needed so that the getHistory method will return a history of all actions as a String.
i. The history should start from the initial 0 value to the last input.
ii. Use the normal operators for the operations (+, -, *, /). There is no limit on the size of the String returned.
iii. The return String should separate all operations and values with a space.
iv. For example, if the following actions are done,
myCalculator.add (4);
myCalculator.subtract (2);
myCalculator.multiply (2);
myCalculator.add(5);
then the value returned should be 0 + 4 – 2 * 2 + 5
v. Add other variables as needed to the class. Make changes to the other methods as needed.
Calculator.java
Explanation / Answer
1.
package cse360assign3;
public class Calculator {
private int total;
public Calculator () {
total = 0; // not needed - included for clarity
}
public int getTotal () {
return total;
}
public void add (int value) {
total = total +value;
}
public void subtract (int value) {
total = total -value;
}
public void multiply (int value) {
total = total*value;
}
public void divide (int value) {
if(value == 0)
total =0;
else
total = total/value;
}
public String getHistory () {
return "";
}
}
2.
package cse360assign3;
public class Calculator {
private int total;
StringBuffer history;
public Calculator () {
total = 0; // not needed - included for clarity
history = new StringBuffer("0");
}
public int getTotal () {
return total;
}
public void add (int value) {
total = total +value;
history.append(" + "+value);
}
public void subtract (int value) {
total = total -value;
history.append(" - "+value);
}
public void multiply (int value) {
total = total*value;
history.append(" * "+value);
}
public void divide (int value) {
if(value == 0)
total =0;
else
total = total/value;
history.append(" / "+value);
}
public String getHistory () {
return history.toString();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.