implementation of simple calculator - java

Create a program which simulates a very simple calculator
So I have been asked to implement an abstract class that represents binary (having 2 arguments) arithmetic expression
abstract class ArithmeticExpression {
double binary1;
double binary2;
public abstract void evaluate ();
public abstract void display ();
}
so then I created sub classes add, multiply, subtract, and divide. In subtract I have:
public class subtract extends ArithmeticExpression {
// private double result;
double binary1;
double binary2;
public subtract (double x, double y) {
this.binary1 = x;
this.binary2 = y;
}
public void evaluate () {
System.out.println("Expression: " + getsubX() + " - " + getsubY() + " = ");
// return result;
}
public void display () {
}
public double getsubX() {
}
public double getsubY() {
}
Using the classes I should be able to represent any arbitrary expression, with no hard coding.
It is also said evaluate should return the result as double and display method should print the expression out in string. Am I on the right track? What am I missing here? The part I do not understand how it is able to represent any expression?

Using your abstract ArithmeticExpression, here's what the Subtract class should look like. Java classes start with a capital letter.
public class Subtract extends ArithmeticExpression {
double result;
public Subtract(double x, double y) {
this.binary1 = x;
this.binary2 = y;
}
#Override
public void evaluate() {
result = binary1 - binary2;
}
#Override
public void display() {
System.out.println("Expression: " + binary1 +
" - " + binary2 + " = " + result);
}
}
You don't have to re-declare binary1 and binary2. They are instantiated in the abstract ArithmeticExpression class.
You do have to provide a double for the result. This should have been done in the abstract ArithmeticExpression class.
The evaluate() method is for evaluation.
The display() method is for display.
You don't have to define any other methods in your Subtract concrete class.

If you want to evaluate any expession inserted in form of
4 + 3 * ( 4 + 5)
You either need to create binary tree or stack and fill those values and operators in.
What I quite dont understand is your so called binary represented in double. If you want to have binary calc, you should use unsigned int or long (or any other type, that is not floating point)

Related

How to convert data type of numbers being added together from doubles to string?

For my assignment, I have been asked to create a test harness which provides feedback on whether the following sums are true. For this question, I will only provide one sum as an example. I have been asked to produce the following:
TestCalculator has a method called testParser() which:
Tests that x("12 + 5") returns a Double with the value 17
I have been given a template in which to set this out on which looks like this:
Template
public class TestCalculator {
Double x;
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
//Sum here
return new Double(0);
}
public void testParsing() {
if (//condition) == 17) {
System.out.println("Adding Success");}
else {
System.out.println("Adding Fail");
}
}
And this is what I've managed to come up with so far:
Current program...Main class
public class Main {
public static void main(String[] args) {
TestCalculator call = new TestCalculator();
call.testParsing();
}
}
TestCalculator class
public class TestCalculator {
Double x;
Double doubleObject = 1.0;
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
this.x = 12.0;
x = 5.0;
return new Double(0);
}
public void testParsing() {
if (x(doubleObject) == 17) {
System.out.println("Adding Success");}
else {
System.out.println("Adding Fail");
}
}
}
I have two main queries. Firstly, I have been asked to test if "x("12 + 5") returns a Double with the value 17". I can see that this has been laid out so that the sum is a data type of String and I am confused as to why or how you would perform this calculation using the string data type.
Secondly, Within my current version of the program, the output returns that the adding calculation failed because I cannot access the returned double value of the calculation. But I am unsure of how I would access that value in my if statement and also return the output of the calculation and put it into the Double value that is returned in the method.
I have tried to make the question as clear and concise as possible for the reader to understand, any help on this would be greatly appreciated, thanks.
to return a new value that adds two values consider
public Double x(Double x){
System.out.println("== Adding ==");
//Sum here
this.x = x;
return new Double(x + 5);
}
Called as
if (x(12.0) == 17.0) {

Homework Help Pt2 (Math The Complex Class)

Not sure if I'm doing this right, but this is a continuation of the program I was working on here...Homework Help PT1
I'm struggling a lot with this homework assignment...
**(Math: The Complex class) A complex number is a number in the form a + bi,
where a and b are real numbers and i is 2-1. The numbers a and b are known
as the real part and imaginary part of the complex number, respectively. You can
perform addition, subtraction, multiplication, and division for complex numbers
using the following formulas:
a + bi + c + di = (a + c) + (b + d)i
a + bi - (c + di) = (a - c) + (b - d)i
(a + bi)*(c + di) = (ac - bd) + (bc + ad)i
(a + bi)/(c + di) = (ac + bd)/(c2 + d2) + (bc - ad)i/(c2 + d2)
You can also obtain the absolute value for a complex number using the following
formula:
a + bi = 2a2 + b2
Design a class named Complex for representing complex numbers and the
methods add, subtract, multiply, divide, and abs for performing complexnumber
operations, and override toString method for returning a string representation
for a complex number. The toString method returns (a + bi) as a
string. If b is 0, it simply returns a. Your Complex class should also implement the
Cloneable interface.
Provide three constructors Complex(a, b), Complex(a), and Complex().
Complex() creates a Complex object for number 0 and Complex(a) creates
a Complex object with 0 for b. Also provide the getRealPart() and
getImaginaryPart() methods for returning the real and imaginary part of the
complex number, respectively.
Write a test program that prompts the user to enter two complex numbers and
displays the result of their addition, subtraction, multiplication, division, and absolute
value.**
Here is what I have so far. Two classes...
// ComplexTest.java
import java.util.Scanner;
public class ComplexTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first complex number: ");
double realPart = input.nextDouble();
System.out.println("Enter the second complex number: ");
double imaginaryPart = input.nextDouble();
Complex cn1 = new Complex(realPart, imaginaryPart);
Complex cn2 = new Complex(realPart);
Complex cn3 = new Complex();
if (realPart == 0) {
System.out.println(cn3.toString());
}
if (imaginaryPart == 0) {
System.out.println(cn2.toString());
}
if(realPart != 0 && imaginaryPart != 0) {
System.out.println(cn1.toString());
}
}
}
// Complex.java
import java.util.Scanner;
public class Complex {
// cloneable interface
public interface Cloneable { }
// Instance Real + Getters and Setters (Accessors and Mutators)
private double realPart;
public double getReal() {
return realPart;
}
public void setReal(double real) {
this.realPart = real;
}
// Instance Real + Getters and Setters (Accessors and Mutators)
private double imaginaryPart;
public double getImaginary() {
return imaginaryPart;
}
public void setImaginary(double imaginary) {
this.imaginaryPart = imaginary;
}
// Constructor Method CN1
public Complex(double a, double b) {
realPart = a;
imaginaryPart = b;
}
// Constructor Method CN2
public Complex(double a) {
realPart = a;
imaginaryPart = 0;
}
// Constructor Method CN3
public Complex() { }
// Add Complex Numbers
public Complex add(Complex comp1, Complex comp2) {
double real1 = comp1.getReal();
double real2 = comp2.getReal();
double imaginary1 = comp1.getImaginary();
double imaginary2 = comp2.getImaginary();
return new Complex(real1 + real2, imaginary1 + imaginary2);
}
// Subtract Complex Numbers
public Complex subtract(Complex comp1, Complex comp2) {
double real1 = comp1.getReal();
double real2 = comp2.getReal();
double imaginary1 = comp1.getReal();
double imaginary2 = comp2.getReal();
return new Complex(real1 - real2, imaginary1 - imaginary2);
}
// Multiply Complex Numbers
public Complex multiply(Complex comp1, Complex comp2) {
double real1 = comp1.getReal();
double real2 = comp2.getReal();
double imaginary1 = comp1.getReal();
double imaginary2 = comp2.getReal();
return new Complex(real1 * real2, imaginary1 * imaginary2);
}
// Divide Complex Numbers
public Complex divide(Complex comp1, Complex comp2) {
double real1 = comp1.getReal();
double real2 = comp2.getReal();
double imaginary1 = comp1.getReal();
double imaginary2 = comp2.getReal();
return new Complex(real1 / real2, imaginary1 / imaginary2);
}
// toString to Change Display
public String toString() {
String result;
result = realPart + " + " + imaginaryPart + "i";
return result;
}
}
Here is my updated code after Jan's help. I've created 3 more methods (subtract, multiply and divide). Should I not be using comp1 and comp2 in every method and instead name them separately from each other? The goal is to print the results of each method at the end at the same time. Will these having the same names mess with that?
I'd also like to know when I should implement the cloneable interface.
Lastly, according to the text a complex number actually looks like two numbers separated by a space. (i.e. 3.5 5.0 rather than just 3.5). If I add two more scanner inputs for the second halves of both of complex numbers, I will have to change my code. Will I have to create new getters and setters to receive this number? Such as imaginaryPart2 and realPart2?
Thank you again for all of the help.
Some Topics to dwell upon:
Variable Scope
Parameters passed into a method are visible only throughout that method. So naming your two operands comp1 and comp2 for each and all of your methods is perfectly fine.
But:
Object Orientation
Your methods should only have one parameter. Say your have one instance of Complex named x. And you want to add to that another instance named y. Then given your code, any operation of x.add(x,y) and y.add(x,y) and even z.add(x, y) would yield the same results.
So: Drop one of your paramters. You might want to add nullchecks.
public Complex add(Complex toAdd) {
return new Complex(this.realPart + toAdd.realPart,
this.imaginaryPart + toAdd.imagineryPart);
}
Now you can write
Complex z = x.add(y);
Getters and Setters
As your add / subtract / divide / multiply operations all return a new Complex number, you might want to make Contex immutable - that is: Provide no setters. Complex number can be created through the constructors. You can get new Complex numbers by invoking calculations on existing ones. But you cannot change a number.
So my advice: Remove the setters.
Input of complex numbers
Instead of reading doubles, you might want to think about reading a String and match that string with a regular expression. You could use that as a utility method in your main or even as a consttructor for Complex, allowing to use a String as input.
Consider this method for matching String:
Pattern complexFinder = Pattern.compile("(-?\\d+(\\.\\d*)?)?\\s*([-+]\\s*\\d+(\\.\\d*)?i)?");
Matcher m = complexFinder.matcher(complexString);
if (m.find()) {
double realPart = 0;
double imaginaryPart = 0;
if (m.group(1) != null) {
realPart = Double.parseDouble(m.group(1).replaceAll("\\s", ""));
}
if (m.group(3) != null) {
imaginaryPart = Double.parseDouble(m.group(3).replaceAll("\\s", "").replace("i", ""));
}
Complex c = new Complex(realPart, imaginaryPart);
}
Cloneable
Cloneable is an interface you add to your class declaration:
public class Complex implements Cloneable {
Additionally you should implement a clone() method:
public Object clone() {
return super.clone();
}
toString()
Your assignment requests that an 0 imaginary part be left out in String output. So you might want to check that again. This should be a simple if()

Putting a letter the nth power

Trying to print out a^n but i get the error that a and n aren't defined as variables. Here is what I have now.
public class FermatsTheorem {
public static void main(String[] args) {
fermatsTheorem(a, n);
}
public static void fermatsTheorem(double a, double n){
double aToTheNthPower = Math.pow(a,n);
System.out.println("Fermat's Last Theorem: " + aToTheNthPower);
}
}
You need to declare values for a and n.
Imagine you had an equation x + y = result. How could you know what the value of result is if you don't know the values of x and y?
Same thing for your case. You are trying to compute what a^n equals but you don't give the program any values to compute.
public class FermatsTheorem {
public static void main(String[] args) {
double a = 3.5;
double n = 2.0;
fermatsTheorem(a, n);
}
public static void fermatsTheorem(double a, double n){
double aToTheNthPower = Math.pow(a,n);
System.out.println("Fermat's Last Theorem: " + aToTheNthPower);
}
}
You're looking for a Symbolic Manipulation. This is not a feature of most programming languages. You can't actually deal with abstracts, only concrete values. There are quite possibly libraries available to do what you want in your language of choice, but you may also want to look at something like Mathlab.

I am having problems with compareTo

Well, I need to make a project where I have two interfaces and they are both used in two unrelated classes. I managed to get everything else to work out properly except for the compareTo method. The two classes I have made are Car and Horse. What I am trying to do is compare the milesGoal from Horse to the one in Car and return either a 1, 0, or -1.
However when I try doing this I get the error "double could not be dereferenced"
I have been stuck on this for a while trying to find different ways to approach this part of the code. I tried using compareTo in the tester class instead of making a method but I got the same error and I am required to make it into a method.
This is the Horse Class:
public class Horse implements milesInterface , kilometersInterface{
private double currentMile;
private double currentKilo;
private double milesGoal;
private double kilosGoal;
private String horseBreed;
// CONSTRUCTORS
public Horse(){
currentMile = 0;
currentKilo = 0;
milesGoal = 0;
kilosGoal = 0;
horseBreed = "Unspecified";
}
public Horse(double cm, double ck, double mg, double kg, String hb){
currentMile = cm;
currentKilo = ck;
milesGoal = mg;
kilosGoal = kg;
horseBreed = hb;
}
// MILE METHODS
public double remainingMiles(){ // Finds the remaining miles
return milesGoal-currentMile;
}
public void halfMile(){ // Divides the desired goal halfway (Miles)
milesGoal = milesGoal/2;
}
public void setMileGoal(double newMile){ // Allows you to set a new goal
milesGoal = newMile;
}
public double getMileGoal(){
return milesGoal;
}
// KILOMETER METHODS
public double remainingKilos(){ // Finds the remaining Kilos
return kilosGoal-currentKilo;
}
public void halfKilo(){ // Divides the desire goal halfway (Kilos)
kilosGoal = kilosGoal/2;
}
public void setKiloGoal(){ // Allows you to set a new goal
kilosGoal = milesGoal*1.6;
}
public void setCurrentKilo(){ // Allows you to set the current Kilo
currentKilo = currentMile * 1.6;
}
// UNIQUE METHODS
public double getMilesStatus(){
return currentMile;
}
public double getKilosStatus(){
return currentKilo;
}
public String getHorseBreed(){
return horseBreed;
}
public void convertToKilos(){ // Converts current miles to kilometers
double kilos = currentMile * 1.6;
System.out.println("The current miles to kilometers is: " + kilos + "km.");
}
public void convertToMiles(){ // Converts current kilometers to miles
double miles = currentKilo * .6;
System.out.println("The current kilometers to miles is: " + miles + "m.");
}
public void milesPerHour(double hours){ // Calculates the mph to the goal by a time
double answer = milesGoal / hours;
System.out.println("The mph needed to reach the desination in " + hours + " hours: " + answer);
}
public void kilosPerHour(double hours){ // Calculates the kmph to the goal by a time
double answer = kilosGoal / hours;
System.out.println("The kilometers needed to reach the desination in " + hours + " hours: " + answer);
}
public int compareTo(Object Other){
if(milesGoal > (Horse)milesGoal.Other)
return 1;
if(milesGoal < (Horse)milesGoal.Other)
return 0;
return -1;
}
}
The Car class is pretty much the same as the Horse one and I need to find a way to compare both of their milesGoal to see which one is greater. I tried multiple things but it doesn't seem to work
This is the interface I made:
abstract interface milesInterface{
public double remainingMiles();
public void halfMile();
public void setMileGoal(double newMile);
public int compareTo(Object Other);
}
abstract interface kilometersInterface{
public double remainingKilos();
public void halfKilo();
public void setCurrentKilo();
public int compareTo(Object Other);
}
First, you are writting attribute.object. This is what fails. Other.milesGoal is a better option.
Another problema is with the casting. What you are doing is trying to cast milesGoal.other to Horse (you want to cast milesGoal)
You should use
if (milesGoal > ((Horse) other).milesGoal)
Also, use proper capitalization (variables go in lowercase, clases/interfaces in uppercase) and setters and getters.
Additionally, you probably will want to cast to the interface so you can use the methods with other clases that implement it
if (milesGoal > ((MilesInterface) other).milesGoal)
Firstly, (Horse)milesGoal.Other should be ((Horse) Other).milesGoal.
I would suggest overloading compareTo with one method for comparing to Horses and one method for comparing to Cars. Then your code looks like
public int compareTo(Horse horse){
if(milesGoal > horse.milesGoal)
return 1;
if(milesGoal < horse.milesGoal)
return -1;
return 0;
}
public int compareTo(Car car){
if(milesGoal > car.milesGoal)
return 1;
if(milesGoal < car.milesGoal)
return -1;
return 0;
}

Java - function as parameter

I read the next answer about passing function as parameter.
Still, I don't get the idea. My function can get any function: sin(x), cos(x), etc.
As I understood, I can create an interface, for example:
public interface functionI<T> {
}
that would wrap It.
Now I have my function:
public void needToDo(functionI<Integer> a, int x0Par, int hPar){
}
(needToDo, for example, need to substitue the x of the function n x0par and hPar, and find the Max. If I got sin(x), I need to find the max of sin(x0Par) and (sin(hPar)).
I didn't understand how I use it in my function. How will I know what to do when I got the function, that can be anything (polynomial, sin(x), and so on)
Something like this:
public interface Function1<RESULT,INPUT> {
RESULT call(INPUT input);
}
public class Sin implements Function1<Double,Double> {
public static final Sin instance = new Sin();
private Sin() {
}
public Double call(Double x) {
return Math.sin(x);
}
}
public Double needToDo(Function1<Double,Double> aFunction, Double x0Par, Double hPar) {
Double d1 = aFunction.call(x0Par);
Double d2 = aFunction.call(hPar);
return d1 > d2 ? d1 : d2;
}
public static void main(String[] args) {
Double x0Par = 10.2;
Double hPar = 1.9;
Double ret = needToDo(Sin.instance, x0Par, hPar);
System.out.println(ret);
}
It doesn't quite work like that; you cannot pass arbitrary functions as parameters in Java, instead you pass objects which have specific, often generic sounding, functions.
So you could define a MathOperation interface, which has an execute method, taking a double and returning a double.
public interface MathOperation {
double execute(double x);
}
and then you can create
public class Sin implements MathOperation {
public double execute(double x) { return Math.sin(x); }
}
and have a function that uses it like
public void needToDo(MathOperation op, double x) {
System.out.println(op.execute(x));
}
You could create an on-the-fly function for needToDo like
...
needToDo(new MathOperation() {
public double execute(double x) { return x * 2.0; }
});
...
But you can't pass Math.sin as a parameter. There are reflection tricks you can do, but that's another issue.

Categories

Resources