I have this calculator .java from an online practice and I need to test it in JUnit in Eclipse;
package calculator;
import java.util.Scanner;
public class Calculator {
private double accumulator;
public Calculator() { }
public Calculator(double initialValue) { accumulator = initialValue; }
public void add(double number) { accumulator += number; }
public void subtract(double number) { accumulator -= number; }
public void multiply(double number) { accumulator *= number; }
public void divide(double number) { accumulator /= number; }
public void sqrt() { accumulator = Math.sqrt(accumulator); }
public void setAccumlator(double accumulator) { this.accumulator = accumulator; }
public double getAccumulator() { return accumulator; }
#Override
public String toString() { return "Result:" + accumulator; }
}
I've been pouring through documentation (I'm rather new to programming in general) and unsure of how to actually do this. I have JUnit set up and a test file set up, like;
#Test
public void testAdd(){
}
#Test
public void testDivideByZero(){
}
etc.
I've tried a few things and the syntax was wrong, stuff like
The method add(double) in the type Calculator is not applicable for the arguments (double, double)
or
Cannot make a static reference to the non static method add(double) from the type Calculator
Any suggestions?
Example of a test
private Calculator mCalculatorInstance;
#Before
public void setupTestEnvironment() {
// This method will be call before every single test.
mCalculatorInstance = new Calculator(2.0);
}
#Test
public void testAdd(){
mCalculatorInstance.add(2.0); // add 2 to the initial value of 2 which I instanitiate above should return 4.
assertEquals("Adding 2 to 2 should give me 4.", 4.0, c.getAccumulator());
}
In order to do testing, you need to know the expected output of the test. Let use the above test as scenario. I declared that I'm initializing a calculator object with accumulator value of 2.
mCalculatorInstance = new Calculator(2.0);
I know that using the add method of the instance will add the parameter to the accumulator. Hence I call the add method.
mCalculatorInstance.add(2.0);
So now I'm adding 2.0 to the accumulator which already have a value of 2.0
2.0 + 2.0 = 4.0
Since the object provide a method to get back the accumulator, I use the method to get back accumulator and check whether the addition is correct, the value of accumulator should be 4.0.
assertEquals("Adding 2 to 2 should give me 4.", 4.0, c.getAccumulator());
Related
I wonder if there is a way (a gradle script or any script or any other way without an IDE) to remove methods annotated with certain annotations. Example:
class x {
public static void main(String[] args) {
int x = getValue();
System.out.println(x);
}
#RemoveEnabled(id = "getValueMethod1", return = "10")
int getValue() {
return 20;
}
}
Now when I run the script or gradle target, it should remove the getValue() method, and the output code should become:
class x {
public static void main(String[] args) {
int x = 10;
System.out.println(x);
}
}
Is there an existing script or way to achieve this? It might be achievable with grep and String parsing etc., but I'm looking for a cleaner solution which is able to get all methods by an annotation id, and remove them with formatting. I tried searching on Google, Stack Overflow etc., but couldn't find a solution.
I wrote a module to process similiar task.
https://github.com/KnIfER/Metaline
#StripMethods(keys={"ToRemove","AlsoRemove"})
public class YourCLZ{
void ToRemove(){} // will be removed
void AlsoRemove(){} // will be removed
#StripMethods(strip=true)
void AnotherTest(){} // will also be removed
}
in your case
#StripMethods(keys="getValue")
class yourx {
public static void main(String[] args) {
int x = getValue();
System.out.println(x);
}
int getValue() {
return 20;
}
}
will become:
class yourx {
public static void main(String[] args) {
System.out.println(x);
}
}
you will get a compilation error since for now my module simply remove any methods or method body statements that contain the key you specified.
Problem Description:
I want to be able to pass around a list of methods to other classes where the methods have been defined in only one class. If the methods, some of which have input parameters and non-void return types, are defined in one class, I want to be able to pass a list of some of them, with possible duplicates, as a parameter to some other class's constructor.
Code Description:
The code below is a crude example and can be ignored if it detracts from the main goal. Another example, in addition to the one below, would be a case where the methods are int Add(int n1, int n2), int Subtract(int n1, int n2), Multiply, etc.. and the interface has a method called int MathOperation(int n1, int n2).
Attempt to solve the problem:
The adapter pattern seems to have the functionality I'm looking for but I have only seen examples where the methods in the interface have no input or output parameters. An example implementation I wrote just for this question is posted below.
Problem Analogy:
You have a random picture generator web service. There are 30 mutations that can be applied to an image. The client connects and clicks a "generate" button and a random list of some of those functions are passed to some other class within the web service which then proceeds to run those functions with it's own data while also collecting and possibly re-using the return values to generate some mutated cat image. It can't just explicitly call the methods in the other class because that process needs to be done randomly at run-time. That is why I lean towards the idea of generating a random list of methods which are executed in-order when the 'generate' button is clicked.
I hope I have been clear.
public class SomeClass {
...
public double UseWrench(double torque, boolean clockwise) { ... }
public double UsePliers(double torque, boolean clockwise) { ... }
public double UseScrewDriver(double torque, boolean clockwise) { ... }
public boolean UseWireCutters(double torque) { ... }
interface IToolActions {
double TurnFastener(double torque, boolean clockwise);
boolean CutWire(double torque);
}
private IToolActions[] toolActions = new IToolActions[] {
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UseWrench(double torque, boolean clockwise); } },
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UsePliers(double torque, boolean clockwise); } },
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UseScrewDriver(double torque, boolean clockwise); } },
new IToolActions() { public boolean CutWire(double torque) { boolean UseWireCutters(double torque); } },
};
}
public class Worker<T> {
public List<? extends IToolActions> toolActions;
public Worker(List<? extends IToolActions> initialToolSet){
toolActions = initialToolActions;
}
}
While #alainlompo has the general idea, Java 8 simplifies this greatly by using something such as BiConsumer (for doubles) or even just a Consumer for the class object. In fact, you can go really crazy, and have a method accept varargs lambdas:
public class SomeClass
public double useWrench(double torque, boolean clockwise) { ... }
public double usePliers(double torque, boolean clockwise) { ... }
public double useScrewDriver(double torque, boolean clockwise) { ... }
public boolean useWireCutters(double torque) { ... }
}
public class Worker {
#SafeVarargs
public Worker(SomeClass example, Consumer<? extends SomeClass>... operations) {
for (Consumer bc : operations) {
bc.accept(example);
}
}
}
Then, this is easily simplified:
SomeClass c = new SomeClass();
new Worker(c, SomeClass::useWrench, SomeClass:usePliers, SomeClass::useScrewDriver, SomeClass::useWireCutters);
While it seems a little awkward applying it like that (due to it being an Adapter pattern), you can easily see how this could apply to a class body:
public class SomeClass
public double useWrench(double torque, boolean clockwise) { ... }
public double usePliers(double torque, boolean clockwise) { ... }
public double useScrewDriver(double torque, boolean clockwise) { ... }
public boolean useWireCutters(double torque) { ... }
#SafeVarargs
public void operate(Consumer<? extends SomeClass>... operations) {
for (Consumer<? extends SomeClass> bc : operations) {
bc.accept(example);
}
}
}
//Elsewheres
SomeClass c = new SomeClass();
c.operate(SomeClass::useWrench, SomeClass:usePliers, SomeClass::useScrewDriver, SomeClass::useWireCutters);
Of course, you don't need varargs, it will work just as well simply passing a Collection
But wait there's more!!!
If you wanted a result, you can even use a self-returning method via a Function, e.g.:
public class SomeClass {
public double chanceOfSuccess(Function<? super SomeClass, ? extends Double> modifier) {
double back = /* some pre-determined result */;
return modifier.apply(back); //apply our external modifier
}
}
//With our old 'c'
double odds = c.chanceOfSuccess(d -> d * 2); //twice as likely!
There's so much more flexibility provided from the Function API in java 8, making complex problems like this incredibly simplified to write.
#John here is how I have approached a solution to your problem.
I used the case of MathOperations to make it simpler. I think first that I would be better to have the interface outside of SomeClass like:
public interface MathOperable {
public int mathOperation(int n1, int n2);
}
I created two examples of classes implementing this interface and one anonymous implementation inside SomeClass (I did an Add, Multiply and an anonymous "Substract")
public class Add implements MathOperable {
public int mathOperation(int n1, int n2) {
return n1 + n2;
}
public String toString() {
return "<addition>";
}
}
The overriding of toString() is simply for the purpose of giving more readability to the examples that I will show at the end of my post.
public class Multiply implements MathOperable {
public int mathOperation(int n1, int n2) {
// TODO Auto-generated method stub
return n1 * n2;
}
public String toString() {
return "<multiplication>";
}
}
Here is my SomeClass class, it contans a getRandomListOfOperations, where I simulate what happens when the click on the button is done
public class SomeClass {
private static MathOperable addition = new Add();
private static MathOperable multiplication = new Multiply();
// Anonymous substraction
private static MathOperable substraction = new MathOperable() {
public int mathOperation(int n1, int n2) {
// TODO Auto-generated method stub
return n1-n2;
}
public String toString() {
return "<substraction>";
}
};
public List<MathOperable> getRandomListOfOperations() {
// We put the methods in an array so that we can pick them up later randomly
MathOperable[] methods = new MathOperable[] {addition, multiplication, substraction};
Random r = new Random();
// Since duplication is possible whe randomly generate the number of methods to send
// among three so if numberOfMethods > 3 we are sure there will be duplicates
int numberOfMethods = r.nextInt(10);
List<MathOperable> methodsList = new ArrayList<MathOperable>();
// We pick randomly the methods with duplicates
for (int i = 0; i < numberOfMethods; i++) {
methodsList.add(methods[r.nextInt(3)]);
}
return methodsList;
}
public void contactSomeOtherClass() {
new SomeOtherClass(getRandomListOfOperations());
}
}
Now here is my SomeOtherClass (which may correspond to your Worker class)
public class SomeOtherClass<T extends MathOperable> {
Random r = new Random();
List<T> operations;
public SomeOtherClass(List<T> operations) {
this.operations = operations;
runIt();
}
public void runIt() {
if (null == operations) {
return;
}
// Let's imagine for example that the new result is taken as operand1 for the next operation
int result = 0;
// Here are examples of the web service own datas
int n10 = r.nextInt(100);
int n20 = r.nextInt(100);
for (int i = 0; i < operations.size(); i++) {
if (i == 0) {
result = operations.get(i).mathOperation(n10, n20);
System.out.println("Result for operation N " + i + " = " + result);
} else {
// Now let's imagine another data from the web service operated with the previous result
int n2 = r.nextInt(100);
result = operations.get(i).mathOperation(result, n2);
System.out.println("Current result for operation N " + i + " which is " + operations.get(i) +" = " + result);
}
}
}
}
I have a simple test class that contains a main to connect the two classes
public class SomeTestClass {
public static void main(String[] args) {
SomeClass classe = new SomeClass();
classe.contactSomeOtherClass();
}
}
Now a few examples of executions:
And another illustration!
I hope this could be helpful!
Okay, I'm going to be "that guy"... the one who understands the question but asks anyway to restate the problem because I think you are on the wrong path. So, bear with me: if you like what you see, great; if not, I understand.
Basically, you have a different intent/motivation/purpose than what "adapter" is suited for. The command pattern is a better fit.
But first, more generally, one of the goals of designing "elements of reusable software" (from the title of the original GOF design patterns book) is that you don't want to modify code when you add functionality; rather, you want to add code without touching existing functionality. So, when you have:
public class Toolbox {
public void hammer() { ... }
}
and you want to add a screwdriver to your toolbox, this is bad:
public class Toolbox {
public void hammer() { ... }
public void screwdriver() { ... }
}
Rather, ideally, all existing code would remain unchanged and you would just add a new Screwdriver compilation unit (i.e., add a new file), and a unit test, and then test the existing code for regression (which should be unlikely, since none of the existing code changed). For example:
public class Toolbox {
public void useTool(Tool t) { t.execute(); ...etc... }
}
public interface Tool { // this is the Command interface
public void execute() // no args (see ctors)
}
public Hammer implements Tool {
public Hammer(Nail nail, Thing t) // args!
public void execute() { nail.into(t); ... }
}
public Screwdriver implements Tool {
public Screwdriver(Screw s, Thing t)
public void execute() { screw.into(t); ... }
}
Hopefully it should become clear how to extend this to your example. The Worker becomes straight-foward list of Tools (or, for clarity, instead of "Tool" , just call it a "Command").
public class Worker {
public List<Command> actionList;
....
public void work() {
for(...) {
action.execute();
}
}
}
This pattern also allows for easy "undo" functionality and "retry", as well as memoization (caching results so they don't have to be re-run).
Basically im coding a differential equation solver class that will take equations from an "Equation" Class and solve it using the rK4 method.
The main problem Im running into, is that I can't find a way to send a method to another class without extending and gaining acess through inheritance, or making a specefic instance of that Equation methods in my ODE class.
for example, how would I make the code below work? (remember I am not allowed to make a specific instance of Equation methods within the ODE class):
public class Equations {
public double pressureDrp( double a, double b) {
return a+b; //this is just a dummy equation for the sake of the question
}
public double waffles( double a, double b) {
return a-b; //this is just a dummy equation for the sake of the question
}
}
public class ODE {
//x being a method being passed in of "Equations" type.
public double rK4( Equation method x ) {
return x(3, 4);
//this would return a value of 7 from the pressureDrp method in class Pressure
//if I had passed in the waffles method instead I would of gotten a value of -1.
}
}
I would use an interface to encapsulate the concept of a binary method and to allow call-backs, something like:
interface BinaryEquation {
double operate(double d1, double d2);
}
This could then be placed in your equations class like so:
class Equations {
public static class PressureDrop implements BinaryEquation {
#Override
public double operate(double d1, double d2) {
return d1 + d2;
}
}
public static class Waffles implements BinaryEquation {
#Override
public double operate(double d1, double d2) {
return d1 - d2;
}
}
}
And used like so:
class ODE {
public double rk4(BinaryEquation eq) {
return eq.operate(3, 4);
}
}
Or better like so:
public class BinaryTest {
public static void main(String[] args) {
System.out.println("PressureDrop(3, 4): " + new Equations.PressureDrop().operate(3, 4));
System.out.println("PressureDrop(3, 4): " + new Equations.Waffles().operate(3, 4));
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
force base class to use its own method and not overrided method
Suppose I have these classes — sorry, it's kind of hard to think of a simple example here; I don't want any why-would-you-want-to-do-that answers! –:
class Squarer
{
public void setValue(int v)
{
mV = v;
}
public int getValue()
{
return mV;
}
private int mV;
public void square()
{
setValue(getValue() * getValue());
}
}
class OnlyOddInputsSquarer extends Squarer
{
#Override
public void setValue(int v)
{
if (v % 2 == 0)
{
print("Sorry, this class only lets you square odd numbers!")
return;
}
super.setValue(v);
}
}
// auto s = new OnlyOddInputsSquarer();
OnlyOddInputsSquarer s = new OnlyOddInputsSquarer();
s.setValue(3);
s.square();
This won't work. When Squarer.square() calls setValue(), it will go to OnlyOddInputsSquarer.setValue() which will reject all its values (since all squares are even). Is there any way I can override setValue() so that all the functions in Squarer still use the method defined there?
PS: Sorry, Java doesn't have an auto keyword you haven't heard about! Wishful thinking on my part.
Edit: I can't modify Squarer!
It seems to me that the class Squarer is not well designed. If you really need a dirty trick to make this work, you could also override the method square():
class OnlyOddInputsSquarer extends Squarer
{
#Override
public void setValue(int v)
{
if (v % 2 == 0)
{
print("Sorry, this class only lets you square odd numbers!")
return;
}
super.setValue(v);
}
#Override
public void square()
{
super.setValue(getValue() * getValue());
}
}
But... a square of a odd number is not even, so this should not really be a problem. I suppose this is just an example and your real problem is different.
Edit: OK, if this doesn't work, there is even a dirtier method: in setValue check the stack and if it was called from square call super.setValue instead. I don't recommend this, but If you really really need to get this done, check here to see how to do it.
This would be relatively painless solution I think. It postpones the check until the actual squaring is done.
public class OnlyOddInputsSquarer extends Squarer {
#Override
public void square() {
if (getValue() % 2 == 0) {
throw new IllegalStateException("Sorry, this class only lets you square odd numbers!")
}
super.square();
}
}
And here is its unit test (requires JUnit):
public class OnlyOddInputsSquarerTest {
#Test
// normally this case would be in a separate test
public void testSuperclass() {
Squarer squarer = new Squarer();
squarer.setValue(3);
squarer.square();
Assert.asserEquals(9, squarer.getValue());
}
#Test
public void testOddValue() {
OnlyOddInputsSquarer oddSquarer = new OnlyOddInputsSquarer();
oddSquarer.setValue(3);
try {
oddSquarer.square();
Assert.fail("Expected IllegalStateException");
catch(IllegalStateException e) {
// expected
}
}
#Test
public void testEvenValue() {
OnlyOddInputsSquarer oddSquarer = new OnlyOddInputsSquarer();
oddSquarer.setValue(4);
oddSquarer.square();
Assert.asserEquals(16, squarer.getValue());
}
}
In two days i have an exam in java, and i can not figure out the answer to this question:
class ClassA {
public String foo(Integer x , int y) {
return "Integer, int";
}
public String foo(int x, Double y) {
return "int, Double";
}
public String foo(Number x, Number y) {
return "Number, Number";
}
public String foo(Object x, Object y) {
return "Object, Object";
}
public static void main(String... args) {
ClassA a = new ClassA();
System.out.print(a.foo(5, 1.2f) + " ");
System.out.println(a.foo(null, null));
}
}
What's the output?
The Answer is:
Number, Number Number, Number
I know that java always chooses the most specified Method, that is why a.foo(null,null); will envoke the Number,Number Method and not the Object,Object Method.
But why does a.foo(5,1.2f); also envoke the Number,Number Method and not the int,Double Method??
But one more thing which might be helpful:
If i remove the f after 1.2, so that the call is:
a.foo(5,1.2);
I get a compiler error, that it can not choose between the Number,Number and int,Double Method...
Would be really helpful, if you guys could explain that to me :)
1.2f is not wrapped by a Double, it's wrapped by a Float. SinceFloat is not a subclass of Double (they are distinct subclasses of Number), the most specific method signature that can be used is foo(Number,Number).
Once you remove the f, 1.2 will be treated a double (the primitive, not the wrapper class) by default, which can be autoboxed to a Double. However the 5 can also be autoboxed to an Integer, thus causing the ambiguity.
There are two important factors here.
First, 1.2f is not a Double. It's a Float. The (int, Double) function doesn't match at all. (Number, Number) is the best fit.
Second, even when you change it to 1.2 it is still not a Double. It is a double. That is, it's a primitive, not an object. Now, Java will still happily pass a double into a function that wants a Double without much complaint, but in this case you've confused it by giving it two valid conversions it could make:
Convert 5 to an Integer and convert 1.2 to a Double
Leave 5 as a primitive int but convert 1.2 to a Double.
There isn't a rule for which of those is preferable. Java produces a compiler error that it has an ambiguous function call, and forces you to choose which one you'd prefer (by manually wrapping one or both of them in objects).
As an aside, if you had a method that took (int, double) there would be no ambiguity at all: that method actually matches the existing types of 5 and 1.2, so it would be called. It's the fact that some of the arguments here are wrapper objects that causes the mayhem.
Generic Answer:
public class OverloadingNumeric {
public void print(int x){
System.out.println("int");
}
public void print(long x){
System.out.println("long");
}
public void print(float x){
System.out.println("float");
}
public void print(double x){
System.out.println("double");
}
public void print(Integer x){
System.out.println("Integer");
}
public void print(Long x){
System.out.println("Long");
}
public void print(Float x){
System.out.println("Float");
}
public void print(Double x){
System.out.println("Double");
}
public void print(Number x){
System.out.println("Double");
}
public void print(Object x){
System.out.println("Object");
}
public static void main(String[] args) {
OverloadingNumeric obj = new OverloadingNumeric();
/*
* Primitives will take more precedence
* of calling instead of wrapper class arguments,
*/
obj.print(10);
obj.print(10l);
obj.print(10f);
obj.print(10d);
obj.print(10.1);
//obj.print(999999999999999); Error: this letral type int is out of range
obj.print(999999999999999l);
/*
* OUTPUT
* int
* long
* float
* double
* double
* long
*/
/*
* Assume all primitive argument methods
* are commented. then calling the same again
*/
obj.print(10);
obj.print(10l);
obj.print(10f);
obj.print(10d);
obj.print(10.1);
//obj.print((Double)10); //Cannot cast int to Double
obj.print((double)10); //Success
//obj.print((Float)10); //Cannot cast int to Float
obj.print((float)10); //Success
//obj.print(null); ERROR AMBIGUOUS
/*
* OUTPUT
* Integer
* Long
* Float
* Double
* Double
* Double
* Float
*
*/
}
}
interface SuperIfc {}
class SuperClass implements SuperIfc{}
class SubClass extends SuperClass {}
public class OverloadingTest {
public void print(SuperIfc x){
System.out.println("SuperIfc");
}
public void print(SuperClass x){
System.out.println("SuperClass");
}
public void print(SubClass x){
System.out.println("SubClass");
}
public void print(Object x){
System.out.println("Object");
}
public static void main(String[] args) {
OverloadingTest obj = new OverloadingTest();
SuperClass superObj = new SuperClass();
SubClass subObj = new SubClass();
obj.print(superObj);
obj.print(subObj);
obj.print(null);
obj.print((SuperIfc)superObj);
obj.print((SuperIfc)subObj);
obj.print((SuperIfc)null);
/*
* OUTPUT
* SuperClass
* SubClass
* SubClass
* SuperIfc
* SuperIfc
* SuperIfc
*/
}
}