static method from abstract class - java

i have abstract class Figures and 2 inheritors. Triangle, Square and Rectangle.
I need to create a static method which will use the array of figures and return the sum of their areas.
abstract class Figure {
abstract double calculatePerimeter();
abstract double calculateArea()
public class Rectangle extends Figure {
double a;
double b;
public Rectangle(double a, double b) {
this.a = a;
this.b = b;
}
#Override
double calculatePerimeter() {
return 2 * (a + b);
}
#Override
double calculateArea() {
return a * b;
}
}
public class Triangle extends Figure {
double a;
double b;
double c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
#Override
double calculatePerimeter() {
return a + b + c;
}
#Override
double calculateArea() {
double p = calculatePerimeter() / 2.0;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
So I should create a list of figures and use in in the method, but it doesn't work
Figure[] figures=new Figure[3];
figures[1]=new Square(4.6);
figures[2]=new Rectangle(4.5,5.2);
figures[3]=new Triangle(6,5,2.2);
public static double findSquare(????????) {
return square.calculateArea() + rectangle.calculateArea() + triangle.calculateArea();
How should it work and which topic should i read?
Please explain

Since you use inheritance and you implement calculateArea on every sub-figure (square, rectangle, triangle), all you have to do is iterate over the array of figures and sum the calculateArea on all the figures:
public static double findSquare(Figure[] arr) {
double sum = 0;
for (int i : arr) {
sum = sum + arr[i].calculateArea();
}
return sum;
Note: I really think you should read and understand how to work with Java Inheritance and with Arrays

You shoud loop/stream on the array then map each element to area value by calling polymorphic method calculateArea and finally make the sum.
Example with java streams :
double sumOfArea = Arrays.stream(arrayOfFigure).mapToDouble(Figure::calculateArea).sum()

Related

how to solve The method add(double, double, int, double) in the type main is not applicable for the arguments (double, double, double, double)

if you are replying pls show me code and tips
the code comes from bro code and im still learnin sorry
i have fixed a couple of other errors but it still doesn't work
public class main {
public static void main(String[] args) {
double x = add(1.0,2.0,3.0,4.0);
System.out.println(x);
}
static int add (int a , int b) {
System.out.println("this is a overloaded method #1");
return a + b;
}
static int add (int a , int b, int c) {
System.out.println("this is a overloaded method #2");
return a + b + c;
}
static int add (int a , int b, int c, int d) {
System.out.println("this is a overloaded method #3");
return a + b + c + d;
}
static int add (double a , double b) {
System.out.println("this is a overloaded method #4");
return a + b;
}
static int add (double a ,double b, double c){
System.out.println("this is a overloaded method #5");
return a + b + c;
}
static int add (double a , double b, int c, double d) {
System.out.println("this is a overloaded method #6");
return a + b + c + d;
}
}
enter image description here
To fix the errors, you need to do a few things:
In methods 4, 5, and 6 - update the "return type" from int to double (the one which goes after the word static)
In method 6 - update the parameter int c to double c
So your methods 4, 5, and 6 should look like this:
static double add(double a, double b) {
System.out.println("this is a overloaded method #4");
return a + b;
}
static double add(double a, double b, double c){
System.out.println("this is a overloaded method #5");
return a + b + c;
}
static double add(double a, double b, double c, double d) {
System.out.println("this is a overloaded method #6");
return a + b + c + d;
}

Collect averages Java Stream in one shot

I'm trying to find how to collect averages of each field in a list of objects in one liner.
Here is what I'm trying to perform:
public class Value {
int a;
int b;
int c;
// rest of the class
}
Now let's assume I have List<Value> values = getMillionValues();
I know that to get average for one field, I can do following:
int averageOfA = values.stream().mapToInt(Value::getA).average()
What do I need to do in order to get averages for all values w/o repeating line above for each variable?
Maybe there are some other libraries, like Guava, that can help to perform these kind of operations?
Seriously, use a for loop.
int count = 0, sumA = 0, sumB = 0, sumC = 0;
for (Value v : values) {
sumA += v.getA();
sumB += v.getB();
sumC += v.getC();
count++;
}
double avgA = ((double) sumA) / count;
double avgB = ((double) sumB) / count;
double avgC = ((double) sumC) / count;
Seriously, use the code above.
Having said that you should use the code above, you can do it with a stream.
You need a few value holders (the average is a double, so your Value class can't store the averages):
class AveragesResult {
public final double a, b, c;
public AveragesResult(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class AveragesIntermediate {
public final double a, b;
public AverageIntermediate(double a, double b) {
this.a = a;
this.b = b;
}
}
Now that we have the boilerplate out of the way (for good measure, you should implement hashCode, equals and toString, and add some getters), we can finally write the stream in a short and compact way:
values.stream().collect(teeing(
teeing(averagingInt​(Value::getA), averagingInt​(Value::getB), AveragesIntermediate::new),
averagingInt(Value::getC),
(ir, avgC) -> new AveragesResult(ir.a, ir.b, avgC));
Wasn't that hard, right? Make sure you have statically imported all the Collector functions (it looks a lot uglier with all those Collectors.) and you are using Java 12 (Collectors.teeing is new in Java 12).
Don't use that, use a good old for loop.

How to get the goldenRatio using recursion in Java?

I'm working on this simple java recursion problem given the following directions:
Calculate the golden ratio.
Given two numbers a and b with a > b > 0, the ratio is b / a.
I have done some code but I'm stuck on getting the recursion working properly. Here's my code:
public class MyTesting {
public static void main(String[] args) {
System.out.println(ratio(8 , 4));
}
public static double ratio(int a, int b) {
int goldelRatio = 0;
if(a > b && b > 0){
return goldelRatio = a / b;
}
return goldelRatio;
}
}
How about something like this:
double goldenRatio(double a, double b, double epsilon) {
if(Math.abs((b / a) - ((a + b) / b)) < epsilon) {
return ((a + b) / b);
} else {
return goldenRatio(b, a + b, epsilon);
}
}
This way you achieve what you need in one function, with epsilon deciding how fine the resolution would be.
Also as an added bonus, and although Java doesn't have (at the time of writing this at least) tail recursion optimization, in theory this function could be optimized by tail recursion.
example with hard coded epsilon:
double goldenRatio(double a, double b) {
double epsilon = 0.00001;
if(Math.abs((b / a) - ((a + b) / b)) < epsilon) {
return ((a + b) / b);
} else {
return goldenRatio(b, a + b);
}
}
example run:
public static void main(String[] args) {
double goldenRation1 = goldenRatio(1.0, 1.0);
System.out.println(goldenRation1); // prints 1.618032786885246
System.out.println(goldenRation1 > 1.61800 && goldenRation1 < 1.61806); // prints true
double goldenRation2 = goldenRatio(100.0, 6.0);
System.out.println(goldenRation2); // prints 1.6180367504835589
System.out.println(goldenRation2 > 1.61800 && goldenRation2 < 1.61806); // prints true
}
Yours is not a recursive function, a recursive function that calculates Golden Ratio would look like the one below.
private int MAX_COUNTER = 50;
private int count = 0;
public double ratio(double a, double b) {
count++;
double goldenRatio = b / a;
if (count < MAX_COUNTER) {
return ratio(b, a + b);
}
return goldenRatio;
}
NOTE: I put the counters because given that is a recursive function trying to find a number with infinite decimals, it will cause the JVM to go on StackOverflow :) , so we got to stop it sooner or later.
Recursion mainly means methods calling themself, meaning you should try something like that:
public double recursionMethod(int a, int b){
int c = a+b;
if(Math.abs(ratio(b,a)-ratio(c,b))< (double) 1/42)
return ratio(c,b);
else
return recursionMethod(b,c);
}
1/42 is just your accuracy, you can implement any other breaking condition you like. Call this method in main with arguments (1,1).

More elegant inner methods declarations (without all the clutter)?

I have a recursive method that computes x^n with a certain algorithm, but this is of no importance here. What matters is my helper function which keeps track of recursive calls of this algorithm.
public class FastPot {
public static double fastPotRek(double x, int n) {
class Aux {
private double aux(double x, int n, int c) {
if (n == 0) {System.out.print("It took "+c+" recursive calls to compute "); return 1;}
else return (n % 2 == 0) ? aux(x*x, n/2, c+1)
: x * aux(x, n-1, c+1);
}
}
Aux a = new Aux();
return a.aux(x, n, 0);
}
}
To organize that somewhat I wanted to declare aux inside fastPotRek, and for that you have to use an inner class, whose methods I can't declare static. Because of this I instantiate Aux a = new Aux(); to be able to call aux.
Please tell me there is a way to make this more elegant and show me what I have overlooked... Like beeing able to make aux static somehow or not needing to instantiate Aux.
No need for inner class and no need to make that static as well:
public class FastPot {
//Static, use only from within FastPot
private static double aux(double x, int n, int c) {
if (n == 0) {
System.out.print("It took "+c+" recursive calls to compute ");
return 1;
} else {
return (n % 2 == 0) ? aux(x*x, n/2, c+1)
: x * aux(x, n-1, c+1);
}
}
}
//Your outward interface
public static double fastPotRek(double x, int n) {
return aux(x, n, 0);
}
}
Or if you insist on using an inner class:
public class FastPot {
//Static, use only from within FastPot
private static class Aux {
private static double aux(double x, int n, int c) {
if (n == 0) {
System.out.print("It took "+c+" recursive calls to compute ");
return 1;
} else {
return (n % 2 == 0) ? aux(x*x, n/2, c+1)
: x * aux(x, n-1, c+1);
}
}
}
//Your outward interface
public static double fastPotRek(double x, int n) {
return Aux.aux(x, n, 0);
}
}
I'll post this answer although many people (including me) will not be happy with this. Please don't use this kind of code:
public static double fastPotRek(double x, int n) {
return new Cloneable() {
private double aux(double x, int n, int c) {
if (n == 0) {System.out.print("It took "+c+" recursive calls to compute "); return 1;}
else return (n % 2 == 0) ? aux(x*x, n/2, c+1) : x * aux(x, n-1, c+1);
}
}.aux(x, n, 0);
}
Again, i highly suggest to use a private static method like:
public static double fastPotRek(double x, int n) {
return aux(x,n,0);
}
private static double aux(double x, int n, int c) {
...
}
You have this:
Aux a = new Aux();
return a.aux(x, n, 0);
I would write it like this (Does the same):
return new Aux().aux(x, n, 0);
Edit: I´m done with StackOverflow. You guys don´t want help? I won´t give it. From now on, I will only ask about MY problems, and won´t answer.

Help with Overloaded Methods

I have created a class named Times and I have to construct 4 overloaded methods. I just would like some help understanding overloaded methods and at least maybe some help with the first one. I would really appreciate it. Thanks :)
multiply 2 integers and return the (integer) product
multiply 3 integers and return the (integer) product
multiply 2 double values and return the (double) product
multiply 3 double values and return the (double) product
like this?
public class Times {
public static int multiply(int a, int b) {
return a * b;
}
public static int multiply(int a, int b, in c) {
return multiply(a, b) * c;
}
public static double multiply(double a, double b) {
return a * b;
}
public static double multiply(double a, double b) {
return multiply(a, b) * c;
}
}
"Overloaded methods" just means the methods would all have the same name (and be in the same class). The parameters need to be different either in number or type, however.
Since the all multiply stuff, "multiply" makes sense as a name.
The first one:
multiply 2 integers and return the
(integer) product
So it returns an integer (an int), is named "multiply", takes 2 ints as parameters, that gives us:
int multiply(int a, int b) {
It returns the product, so the body is:
return a * b;
And then we're done with that one:
}
That gives us:
int multiply(int a, int b) {
return a * b;
}
Use the same approach and the same name for the others.
it would look somthing like this :
public class Times {
public int mult(int a, int b) {
return a*b;
}
public int mult(int a, int b, int c) {
return a*b*c;
}
//2 more overloaded versions to come here
}
as for understanding what they mean - when your code is compiled the compiler determines which of the methods (all called the same name) to use by looking at the arguments.
so for instance for something like this
int a = 1;
int b = 1;
Times t = new Times();
t.mult(a,b);
the compiler will pick the 1st of the 2 mult methods i demonstrated, while for this:
int a = 1;
int b = 1;
int c = 2;
Times t = new Times();
t.mult(a,b,c);
it will pick the 2nd (based on the number of arguments)
You can do something like this
public class Times {
public static void main(String[] args) {
System.out.println(multiplyInt(1,2));
System.out.println(multiplyDoubles(2.0,3.0));
}
public static int multiplyInt(int... numbers){
int multiply = 1;
for(int number : numbers ){
multiply = multiply*number;
}
return multiply;
}
public static double multiplyDoubles(double... numbers){
double multiply = 1;
for(double number : numbers ){
multiply = multiply*number;
}
return multiply;
}
}

Categories

Resources