Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What I'm trying to do is to get this line of code to work in my main method:
Expression exp = new Add(new Value(3.2), new Multiply(new Value(4.1),
new Value(7.1)));
Here's my code:
public interface Expression {
public int accept(EvaluationVisitor visitor);
}
My Operation Class
public class Operation implements Expression {
private Expression lhs;
private Expression rhs;
public Operation(Value lhs, Value rhs)
{
this.lhs = lhs;
this.rhs = rhs;
}
public Expression getLHS()
{
return lhs;
}
public Expression getRHS()
{
return rhs;
}
public int accept(EvaluationVisitor visitor) {
return 0;
}
}
Value Class(represents a float value):
public class Value implements Expression {
private float number;
public Value(float number)
{
this.number = number;
}
public String toString()
{
return String.valueOf(number);
}
public float getValue()
{
return number;
}
public int accept(EvaluationVisitor visitor) {
return 0;
}
}
My Add and Multiply methods:
public class Add extends Operation {
private Value lhs;
private Value rhs;
public Add(Value lhs, Value rhs)
{
super(lhs,rhs);
}
public String toString()
{
return String.valueOf(lhs.getValue() + rhs.getValue());
}
public Value add()
{
return new Value(lhs.getValue() + rhs.getValue());
}
}
public class Multiply extends Operation{
private Value lhs;
private Value rhs;
public Multiply(Value lhs, Value rhs)
{
super(lhs,rhs);
}
public String toString()
{
return String.valueOf(lhs.getValue() + rhs.getValue());
}
public Value mul()
{
return new Value(lhs.getValue() * rhs.getValue());
}
}
Here's the line of code again:
Expression exp = new Add(new Value(3.2), new Multiply(new Value(4.1),
new Value(7.1)));
In my line of code that I'm trying to get to work, I want to find a way that the Multiply object can be a value can be taken in as an argument. I know that I could just create the object and then place it there by calling my method that returns a Value object, but a constructor is supposed to set up an object so the state of the object is valid. Is there anyway I could get around this?
You need to make full use of your interface so you can treat the values and operator expressions indiscriminately. Right now you aren't doing that, for example, Operation which takes two Values as arguments but stores them as Expressions.
You also have a problem which is that your subclasses of Operation are declaring duplicate members named lhs and rhs. Perhaps you've already noticed that right now you'll get null pointer exceptions if you try to call methods on Add and Multiply.
Here is a slight redesign:
public interface Expression {
public Value evaluate();
}
public class Value implements Expression {
private final float floatValue;
public Value(float floatValue) {
this.floatValue = floatValue;
}
public float floatValue() {
return floatValue;
}
#Override
public Value evaluate() {
return this;
}
}
public abstract class BinaryOperator implements Expression {
protected final Expression lhs, rhs;
public BinaryOperator(Expression lhs, Expression rhs) {
this.lhs = lhs;
this.rhs = rhs;
}
}
public class Add extends BinaryOperator {
public Add(Expression lhs, Expression rhs) {
super(lhs, rhs);
}
#Override
public Value evaluate() {
return new Value(
lhs.evaluate().floatValue()
+
rhs.evaluate().floatValue()
);
}
}
public class Multiply extends BinaryOperator {
public Multiply(Expression lhs, Expression rhs) {
super(lhs, rhs);
}
#Override
public Value evaluate() {
return new Value(
lhs.evaluate().floatValue()
*
rhs.evaluate().floatValue()
);
}
}
Now you can do
Expression exp = (
new Add(new Value(3.2f), new Multiply(new Value(4.1f), new Value(7.1f)))
);
System.out.println(exp.evaluate().floatValue());
Which outputs 32.309998 (the correct answer).
The above redesign could be further simplified if evaluate simply returned a float.
The constructors take Value objects but Multiply does not extend Value
What you are doing is adding a value to an operation. What you really want to be doing is adding a value to a value (the latter being the result of an operation). So you should do the following:
Expression exp = new Add(new Value(3.2), new Multiply(new Value(4.1),
new Value(7.1)).mul());
Alternatively, you could make your Operation class extend Value and override the getValue() method inside the Multiply class to perform the multiplication and return the value (likewise in the Add class to perform the addition and return the value).
Related
I have an abstract class called Expression which represents the result of a math expression and the class AtomicExpression which represents an operand of a math expression which extends Expression. AtomicExpression class has the method toString(). Inexplicably, whenever I initialize an instance of AtomicExpression then toString() is called automatically even though I didn't call it explicitly. I don't understand how this can be.
Originally I noticed that String.format from toString() was returning an error before toString() would be called, so I decided to add System.out.println inside toString() to see from console each time a call would be made to toString().
This is the code:
public abstract class Expression {
private double expression;
public Expression(double expression) {
this.expression = expression;
}
public abstract double calculate();
public boolean equals(Object o) {
Expression e = (Expression) o;
return this.expression == e.expression;
}
}
public class AtomicExpression extends Expression {
private double operand;
private static final String BLANK = "";
public AtomicExpression(double operand) {
super(operand);
this.operand = operand;
}
public double calculate() {
return this.operand;
}
public String toString() {
String s;
if(this.operand == (int) this.operand) { //the operand is an integer
//s = String.format("%d", this.operand);
System.out.println("this.operand == (int) this.operand");
s = BLANK + this.operand;
return s;
} else { //the num is a double
s = BLANK + this.operand;
return s;
}
}
}
public class Main {
public static void main(String[] args) {
AtomicExpression a = new AtomicExpression(5);
//System.out.println(a);
}
}
Java noob here, i have a program that i want to iterate the number of plugins that has been added in another file, then as long as it's a prefix and postfix calculator i want to check if the symbol in the stack for example is '+' so find Addition class that extended from Operator class and then call doAction(stack.pop(), stack.pop()) , it's because i want to add unlimited methods for calculating more symbols
i tried to use reflection but i couldn't understand how to loop over between names to let the program choose the right method
public class Operator {
public int doAction(int op1, int op2) {
return 0;
}
public String getOperator(String sign) {
return null;
}
public String setOperator() {
return null;
}
}
class Plus extends Operator {
public int doAction(int op1, int op2) {
return op1 + op2;
}
public String setOperator() {
return "+";
}
public String getOperator(String sign) {
if (sign.equals("+")) {
return "+";
} else {
return null;
}
}
}
class Minus extends Operator {
public int doAction(int op1, int op2) {
return op1 - op2;
}
public String setOperator() {
return "-";
}
public String getOperator(String sign) {
if (sign.equals("-")) {
return "-";
} else {
return null;
}
}
}
By reading your requirement I would suggest to use Factory or Abstract Factory design pattern. Basically you want to execute particular class's method based on your parameter. You can create factory class which return your desired class based on parameter you passed and it will do your work. for reference
For symbolic representation of mathematical expressions, I am trying to build a hierarchy of number system classes.
In addition to Integer and Real, I also need classes like Rational and Complex. I want all of these classes to inter-operate seamlessly with each other.
e.g. Adding a Complex number to an Integer would give a Complex number etc.
I made all of them to implement the Number interface. (NOT java.lang.Number)
For being able to add numbers of different types, I tried making hierarchy like following.
Integer extends Rational extends Real extends Complex
This makes an Integer to unnecessarily store imaginary part etc. This overhead is undesired.
Also allowing access to imaginary part of an Integer seems improper.
Can anyone suggest a better design where overhead is avoided and interoperation is still possible?
I'd rather create an interface that has something like getRealPart() and getImaginaryPart(). Then your integer can simply return 0 for getImaginaryPart(). That since you want Integer to "be" a Complex, but you don't want Integer to contain the internal implementation of Complex.
public interface Numberr {
public Numberr plus(Numberr n);
public Numberr minus(Numberr n);
public Numberr multiply(Numberr n);
public Numberr sqrt();
...
public Class<? extends Numberr> getType();
}
/////////////////////////////////////////////
public class Integerr implements Numberr {
protected BigInteger value;
#Override
public Numberr plus(Numberr n) {
if (n instanceof Integerr) {
return value.add(n.value);
} else {
// in case of more broad argument type, use method of that class
return n.plus(this);
}
}
....
}
///////////////////////////////////////////////
public class Rational implements Numberr {
protected BigInteger numerator;
protected BigInteger denominator;
#Override
public Numberr plus(Numberr n) {
if (n instance of Integerr) {
return new Rational(numerator.multiply(n.value), denominator);
} else if (n instanceof Rational) {
return new Rational(numerator.multiply(n.denominator).add(n.numerator.multiply(denominator)), denominator.multiply(n.denominator));
} else {
return n.plus(this);
}
}
....
}
I don't see a problem here. Real number is a complex number, integer is a real number. Complex number can be expressed as a + bi and an integer is a complex number, such that a is an integer and b = 0. So every integer has b and it is equal to 0.
You may however consider using composition (and interfaces) over inheritance:
interface Complex {
Real a();
Real b();
}
interface Real extends Complex {
#Override
default Real b() {
return new Integer(0);
}
}
class Integer implements Real {
public Integer(int value) {
// ...
}
#Override
public Real a() {
return this;
}
// ...
}
The disadvantage of this approach is that Integer class can override b() method, so maybe inheritance would be better, because you can use final keyword on the method:
abstract class Complex {
abstract Real a();
abstract Real b();
}
abstract class Real extends Complex {
#Override
public final Real b() {
return new Integer(0);
}
}
class Integer extends Real {
public Integer(int value) {
// ...
}
#Override
public Real a() {
return this;
}
// ...
}
I have tried to model it myself and I came up with this terrible code below. I am not happy about it, because of the following problems:
Interface - InterfaceImpl antipattern
IntegerNumber has methods such as realPart() or numerator() and denominator()
some numbers (complex and rational) use other numbers, while others (real and integer) use Java primitives
Code:
public class Test {
public static void main(String[] args) {
ComplexNumber complexOne = new ComplexNumber(new RealNumber(1.25), new RealNumber(3));
ComplexNumber complexTwo = new ComplexNumber(new RealNumber(7), new RealNumber(18.875));
System.out.println("adding two complex numbers:");
System.out.println(complexOne.add(complexTwo));
RealNumber realOne = new RealNumber(15.125);
RealNumber realTwo = new RealNumber(7.375);
System.out.println("adding two real numbers:");
System.out.println(realOne.add(realTwo));
System.out.println(realTwo.add(realOne));
System.out.println("adding complex and real number:");
System.out.println(complexOne.add(realOne));
System.out.println(realOne.add(complexOne));
RationalNumber rationalOne = new RationalNumber(new IntegerNumber(1), new IntegerNumber(2));
RationalNumber rationalTwo = new RationalNumber(new IntegerNumber(1), new IntegerNumber(3));
System.out.println("adding two rational numbers:");
System.out.println(rationalOne.add(rationalTwo));
IntegerNumber integerOne = new IntegerNumber(6);
IntegerNumber integerTwo = new IntegerNumber(7);
System.out.println("adding two integers:");
System.out.println(integerOne.add(integerTwo));
System.out.println("adding real number and integer:");
System.out.println(integerOne.add(realOne));
System.out.println(realOne.add(integerOne));
System.out.println("adding complex number and integer:");
System.out.println(integerOne.add(complexOne));
System.out.println(complexOne.add(integerOne));
}
}
// interfaces
interface Complex {
Real realPart();
Real imaginaryPart();
default Complex add(Complex other) {
return new ComplexNumber(
this.realPart().add(other.realPart()),
this.imaginaryPart().add(other.imaginaryPart())
);
}
}
interface Real extends Complex {
double asDouble();
#Override
default Real imaginaryPart() {
return new IntegerNumber(0);
}
default Real add(Real other) {
return new RealNumber(this.asDouble() + other.asDouble());
}
}
interface Rational extends Real {
Integer numerator();
Integer denominator();
#Override
default Real realPart() {
return new RealNumber(1.0d * numerator().asInt() / denominator().asInt());
}
#Override
default double asDouble() {
return realPart().asDouble();
}
default Rational add(Rational other) {
return new RationalNumber(
this.numerator().multiply(other.denominator()).add(this.denominator().multiply(other.numerator())),
this.denominator().multiply(other.denominator())
);
}
}
interface Integer extends Rational {
int asInt();
#Override
default Integer numerator() {
return new IntegerNumber(asInt());
}
#Override
default Integer denominator() {
return new IntegerNumber(1);
}
default Integer add(Integer other) {
return new IntegerNumber(this.asInt() + other.asInt());
}
default Integer multiply(Integer other) {
return new IntegerNumber(this.asInt() * other.asInt());
}
}
// implementations
class ComplexNumber implements Complex {
private final Real realPart;
private final Real imaginaryPart;
public ComplexNumber(Real realPart, Real imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
#Override
public Real realPart() {
return realPart;
}
#Override
public Real imaginaryPart() {
return imaginaryPart;
}
#Override
public String toString() {
return String.format("%s + %si", realPart, imaginaryPart);
}
}
class RealNumber implements Real {
private final double value;
public RealNumber(double value) {
this.value = value;
}
#Override
public Real realPart() {
return this;
}
#Override
public double asDouble() {
return value;
}
#Override
public String toString() {
return "" + value;
}
}
class RationalNumber implements Rational {
private final Integer numerator;
private final Integer denominator;
public RationalNumber(Integer numerator, Integer denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
#Override
public Integer numerator() {
return numerator;
}
#Override
public Integer denominator() {
return denominator;
}
#Override
public String toString() {
return String.format("%s/%s", numerator, denominator);
}
}
class IntegerNumber implements Integer {
private final int value;
public IntegerNumber(int value) {
this.value = value;
}
#Override
public int asInt() {
return value;
}
#Override
public String toString() {
return "" + value;
}
}
I am wondering whether interfaces should be abstract classes with implemented methods being final. In the end, I think it may be better to just go with simple inheritance and ignore the fact that every integer will have a field for imaginary part.
I hope this will give you some ideas.
Is there a way in Java to implement this method?
public static <T extends Number> T doubleOf(T number){
//I don't know...
}
Thanks
As mentioned in other answers, there is no general solution.
Beside others, the operation you want to implement may not be well defined for some Number subclasses. For instance, what is the multiple of AtomicInteger? Is it the same instance with a multiplied value? Or a new instance of AtomicInteger? Or a new plain Integer? Theoretically, there might be a subclass of Number that does not allow to create new instances freely.
You may test the input for some known subclasses and implement the operation for those. Something like this:
#SuppressWarnings("unchecked")
public static <N extends Number> N multiply(N number, int multiplier) {
Class<? extends Number> cls = number.getClass();
if (cls == Integer.class) {
return (N) Integer.valueOf(number.intValue() * multiplier);
}
if (cls == Long.class) {
return (N) Long.valueOf(number.longValue() * multiplier);
}
throw new UnsupportedOperationException("unknown class: " + cls);
}
I am afraid the suppression of warnings will be necessary, in some form.
Unfortunately it is not possible in Java because you can't instantiate an object of type T.
See this section of the Java generics tutorial: http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createObjects
A little bit late, but today i had this same problem.
My solution:
public Number multiply(Number number, int multiplier) {
return new Number() {
#Override
public long longValue() {
return number.longValue() * multiplier;
}
#Override
public int intValue() {
return number.intValue() * multiplier;
}
#Override
public float floatValue() {
return number.floatValue() * multiplier;
}
#Override
public double doubleValue() {
return number.doubleValue() * multiplier;
}
};
}
Simple answer is no. Number have no appropriate methods.
But as long as Number have several well known implementation you can just implement it for all of them. Of course if someone create new one you implementation will fail but it is very unlikely
public static <T extends Number> T doubleOf(T number){
if(number instanceOf Integer){
return (T)(Object)number.intValue()*2;
} ... and so on
}
Although a bit weird, you could use the following:
public static <T extends Number & Multipliable> T doubleOf(T number)
{
}
interface Multipliable<T extends Number>
{
T multiply(Number number);
}
class MyDouble extends Number implements Multipliable<MyDouble>
{
Double d;
public MyDouble(final double d)
{
this.d = new Double(d);
}
#Override
public MyDouble multiply(Number number)
{
return new MyDouble(d.doubleValue() * number.doubleValue());
}
#Override
public double doubleValue()
{
return d.doubleValue();
}
#Override
public float floatValue()
{
return d.floatValue();
}
#Override
public int intValue()
{
return d.intValue();
}
#Override
public long longValue()
{
return d.longValue();
}
}
This could be used like this:
MyDouble result = new MyDouble(2d).multiply(new Short((short) 1));
Is there a "typeof" like function in Java that returns the type of a primitive data type (PDT) variable or an expression of operands PDTs?
instanceof seems to work for class types only.
Try the following:
int i = 20;
float f = 20.2f;
System.out.println(((Object)i).getClass().getName());
System.out.println(((Object)f).getClass().getName());
It will print:
java.lang.Integer
java.lang.Float
As for instanceof, you could use its dynamic counterpart Class#isInstance:
Integer.class.isInstance(20); // true
Integer.class.isInstance(20f); // false
Integer.class.isInstance("s"); // false
There's an easy way that doesn't necessitate the implicit boxing, so you won't get confused between primitives and their wrappers. You can't use isInstance for primitive types -- e.g. calling Integer.TYPE.isInstance(5) (Integer.TYPE is equivalent to int.class) will return false as 5 is autoboxed into an Integer before hand.
The easiest way to get what you want (note - it's technically done at compile-time for primitives, but it still requires evaluation of the argument) is via overloading. See my ideone paste.
...
public static Class<Integer> typeof(final int expr) {
return Integer.TYPE;
}
public static Class<Long> typeof(final long expr) {
return Long.TYPE;
}
...
This can be used as follows, for example:
System.out.println(typeof(500 * 3 - 2)); /* int */
System.out.println(typeof(50 % 3L)); /* long */
This relies on the compiler's ability to determine the type of the expression and pick the right overload.
You can use the following class.
class TypeResolver
{
public static String Long = "long";
public static String Int = "int";
public static String Float = "float";
public static String Double = "double";
public static String Char = "char";
public static String Boolean = "boolean";
public static String Short = "short";
public static String Byte = "byte";
public static void main(String[] args)
{
//all true
TypeResolver resolver = new TypeResolver();
System.out.println(resolver.getType(1) == TypeResolver.Int);
System.out.println(resolver.getType(1f) == TypeResolver.Float);
System.out.println(resolver.getType(1.0) == TypeResolver.Double);
System.out.println(resolver.getType('a') == TypeResolver.Char);
System.out.println(resolver.getType((short) 1) == TypeResolver.Short);
System.out.println(resolver.getType((long) 1000) == TypeResolver.Long);
System.out.println(resolver.getType(false) == TypeResolver.Boolean);
System.out.println(resolver.getType((byte) 2) == TypeResolver.Byte);
}
public String getType(int x)
{
return TypeResolver.Int;
}
public String getType(byte x)
{
return TypeResolver.Byte;
}
public String getType(float x)
{
return TypeResolver.Float;
}
public String getType(double x)
{
return TypeResolver.Double;
}
public String getType(boolean x)
{
return TypeResolver.Boolean;
}
public String getType(short x)
{
return TypeResolver.Short;
}
public String getType(long x)
{
return TypeResolver.Long;
}
public String getType(char x)
{
return TypeResolver.Char;
}
}
There are two ways that you can use to determine the type of the Primitive type.
package com.company;
public class Testing {
public static void main(String[] args) {
int x;
x=0;
// the first method
System.out.println(((Object)x).getClass().getName());
if (((Object)x).getClass().getName()=="java.lang.Integer")
System.out.println("i am int");
// the second method it will either return true or false
System.out.println(Integer.class.isInstance(x));
}
}