Introduction to extending classes [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a class Triangle and a class that extends Triangle that is called IsoscelesRight.
I got this instruction and hint from my teacher to write IsoscelesRight but I'm still unsure as to how to do it.
IsoscelesRight takes just one double value, but sets up the sides so that an isosceles right triangle is formed. Hint: Do this by setting sides a and b to same value, and side c will equal side a times the square root of two. Make sure the constructor appropriately calls super().
public class Triangle
{
private double sideA;
private double sideB;
private double sideC;
public Triangle(double a, double b, double c)
{
sideA = a;
sideB = b;
sideC = c;
}
public double getSideA()
{
return sideA;
}
public double getSideB()
{
return sideB;
}
public double getSideC()
{
return sideC;
}
}
Here's all I have for IsoscelesRight that needs to be changed.
public class IsoscelesRight extends Triangle
{
public IsoscelesRight(double side)
{
super(side, side, side);
}
}

You must be looking for:
public class IsoscelesRight extends Triangle {
public IsoscelesRight(double side) {
super(side, side, Math.sqrt(2) * side);
}
}
I will leave the research as to why to you as this is clearly homework.
Please note that if you just submit this code to your prof you will almost certainly get an f for effort.
A slightly better (and certainly more illuminating) solution would be:
public class Isosceles extends Triangle {
public Isosceles(double side, double hypotenuse) {
super(side, side, hypotenuse);
}
}
public class Right extends Isosceles {
public Right(double side) {
super(side, Math.sqrt(2) * side);
}
}

In any triangle the sides are constrained by Pyphagorean theorem, so if you intend to store sides lenghts you only need to store 2, and the 3rd one (i.e. Hypotenuse) is always computed. This will take less space but take more time to retrieve the hypotenuse as SQRT takes time to compute. So revise your model because it can not just store 3 length for logically-valid triangle (there is no need to take memory for 3 values) without any checks in .ctor.
Just store side A and B, hypotenuse calculate according to formula: A^2 + B^2 = C^2.
If you store all 3 sides then check that values add up according to the formula or your triangle will store logically corrupt data.
If I had been your teacher I would have wanted to at least hear these concerns voiced. The actual class design may be whatever is needed for application - be it speed, performance, logical consistency of data and all combinations of the above.

Related

What's wrong with my code ? Why it is not calculating the area of circle correctly? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
What's wrong with my code ? Why it is not calculating the area of
cirlce correctly in case of circle as a shape? Every time it is
calculating the area of circle equals to 0.Rest of the code is working
fine.
package constructor;
import java.util.Scanner;
class input{
float c_area;
int s_area,r_area;
input(int side1,String type)
{
if(type.equals("circle"))
{
c_area=3.14f*side1*side1;
}
else{
s_area=side1*side1;
}
}
input(int l,int b){
r_area=l*b;
}
void area(String select){
if(select.equals("cirlce"))
{
System.out.println("Area is: "+c_area);
}
else if(select.equals("square")){
System.out.println("Area is: "+s_area);
}
else
{
System.out.println("Area is:"+r_area);
}
}
};
public class shape {
public static void main(String[] args) {
String name;
char ch;
Scanner obj=new Scanner(System.in);
do{
System.out.print("ENTER THE SHAPE TYPE:");
name=obj.next();
if(name.equals("circle"))
{
int radius;
System.out.print("Enter the radius: ");
radius=obj.nextInt();
input a=new input(radius,name);
a.area(name);
}
else if(name.equals("rectangle"))
{
int len,bre;
System.out.print("Enter LENGTH & BREADTH: ");
len=obj.nextInt();
bre=obj.nextInt();
input x=new input(len,bre);
x.area(name);
}
else if(name.equals("square"))
{
int side;
System.out.print("Enter side: ");
side=obj.nextInt();
input x=new input(side,name);
x.area(name);
}
System.out.println("continue: Y or N:");
ch=obj.next().charAt(0);
}while(ch=='y' || ch=='Y');
}
}
What's wrong with my code ? Why it is not calculating the area of
cirlce correctly in case of circle as a shape? Every time it is
calculating the area of circle equals to 0.Rest of the code is working
fine.
The problem is with this piece of code in your input class:
if(type.equals("circle"))
{float c_area;
c_area=3.14f*side1*side1;
}
you are declaring c_area inside if making it local variable and not instance variable, Instead try this
if(type.equals("circle"))
{
this.c_area=3.14f*side1*side1;
}
Hope it helps..
Fist of all it would be better for you to Use "Math.PI" intead of just taking 3.14f it´s more accurate;
In my Oppinoin you should use a static Method to calculate the "c_area" (with the Parametes (radius, Type) and imedietey return that.
I don't see needs to Create an Object so you could delete your Constructor (cause it isn´t needed to work with this Object later.
If this is your whole coode I woult personally just create an Method to calculate the area.. and just don't use another class
he he program is perfectly fine and there is no coding mistake.
only thing is that there is typo in void area(String select){ } method
if(select.equals("cirlce")) should be if(select.equals("circle"))
circle spelling is wrong.
Look at these 2 lines:
float c_area;
c_area=3.14f*side1*side1;
You are declaring a variable named c_area inside the constructor, when you already have a variable named the same way in the class scope declaration. So the compiler ignore the class level variable, and calculates the constructor level variable instead. Of course, the class level variable doesn't change and stays zero by default. Simply remove float c_area; from the constructor and you're good
Notice: if you are new to Java, you should know that it follows certain code conventions. You should name your classes with UpperCase styling, and your variable names should be camelCased

Algorithm mistake, finding areas between lines

I was doing my math hw, and it required me to calculate areas between 2 lines. I solved couple of them, I got them right(its online so it shows me whether i got it wrong or right), then I thought about writing a program that does the calculation for me, I created a nice algorithm, used java for the program, but in the end it didn't give me the right answer.
I put the data from one of the questions I already solved whether i got it right or wrong.
Can you please tell me the mistake in the algorithm??
public class DailyHelper {
public static double f(double x) {
double y = 5*x;
return y;
}
public static double g(double x) {
double y= 4*x*x;
return y;
}
public static void main(String[] args) {
double xLower = 0;
double xHigher = 5/4;
double areaF=0;
double areaG=0;
double change = (xHigher-xLower)/100000;
for(double k=xLower; k<xHigher; k=k+change) {
areaF = areaF+(change*f(k));
}
for(double k=xLower; k<xHigher; k=k+change) {
areaG = areaG+(change*g(k));
}
double area = areaF-areaG;
System.out.println(area);
}
}
Just a quick thought.
Your xHigher variable is always 1, since you're dividing int by int. Try 5/4d
If there are 2 straight random lines and you want to calculate area from vertical lines L1 and L2, L1 < L2, then you must construct that trapezoid (by finding the corner coordinates) and calculate the area. However this doesn't work on non-linear "lines", you'll need to follow a rule like that: http://en.wikipedia.org/wiki/Numerical_integration#Methods_for_one-dimensional_integrals

Is Chain of Rep. appropriate or not [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I was asked in an interview to implement a business rule
Requirements change. They always do:
assess a 20% fee for any amount below $100,000.
assess a 10% fee for any amount between $100,000 and $500,000.
assess a 5% fee for any amount above $500,000
Calculate the fee for an arbitrary amount x.
Example: Given a $600,000 invoice the fee should be $65,000.
Given a $50,000 invoice the fee should be $10,000.
Given a $200,000 invoice the fee should be $30,000.
I used CofR but the interviewer then asked what if their is more than 3 conditions like n of them would i create n-classes to handle each request.
Is their a better approach to the question asides writing a very long recursive function checking for each of the conditions.
CoR is helpful when the members of the chain have substantially different rules, but in this case, all of the rules are basically the same (charge a certain percent if the amount is over X). Instead of independent classes, just have one struct-like class that holds the minimum amount and percentage, and another one that looks up the appropriate fee:
class FeeSchedule {
static class Entry implements Comparable<Entry> {
int threshold;
int percentage;
int compareTo(Entry other) {
// sort by percentage, descending
}
SortedSet<Entry> feeTable;
int calculateFee(int invoiceAmount) {
for(Entry e : feeTable)
if(invoiceAmount > e.threshold)
return (invoiceAmount * e.percentage);
// error condition; return 0?
}
}
I would guess that the interviewer was implying that something like the chain-of-responsibility pattern would be a little over-engineered for a problem like this. There's also an argument that your implementing classes would actually have the same responsibility, in that they'd all be computing an amount based on a given input, just with different parameters.
I would probably do this with two simple classes. One would compute the percentage fee rate based on the input value and one would use this rate to return the fee amount.
If you need to add a fourth condition, you just add it to the class containing the rate computation. I don't see why it needs to be any more complicated than this for such a simple problem.
EDIT:
I was thinking along the same lines as #chrylis in that there'd be a class to perform the calculation by processing an ordered list of rates.
class Rate {
int rangeSize;
double commission;
Rate(int rangeSize, double commission){
this.rangeSize = rangeSize;
this.commission = commission;
}
int computeForAmount(int amount) {
if (amount <= 0) {
return 0;
}
return (int) (Math.min(amount, this.rangeSize) * this.commission);
}
}
class FeeCalculator {
List<Rate> rates = Arrays.asList(
new Rate(100, 0.2),
new Rate(400, 0.1),
new Rate(500, 0.05));
int calculateCommission(int startingAmount) {
int commission = 0;
int remainingAmount = startingAmount;
for (Rate rate : this.rates) {
commission += rate.computeForAmount(remainingAmount);
remainingAmount -= rate.rangeSize;
}
return commission;
}
}
I admit that I'm not entirely happy about breaking the encapsulation by calling rate.rangeSize but it does demonstrate the design I was trying to articulate.
I think a simple strategy pattern should be enough in this case. Something like:
interface FeeAssessor {
public double assessFee(double invoice);
}
FeeAssessor feeAssessor = new FeeAssessor() {
// logic goes here
};
double calculateFee(double invoice) {
return feeAssessor.assessFee(invoice);
}
For a simple business logic that you presented, I think it would be simpler to implement it all inside one assessFee() function. You can implement different (simple) ones and swap out the "strategy" object as needed. If the fee assessment algorithm depends on multiple varying factors that are independent of each other, then you can further split them up into multiple strategy methods.

Calculating math in GPS format

I'm making a Android Application to calculate Math in GPS Format.
Example:
Given
N 48°44.(30x4) E 019°08.[(13x31)+16]
the App calculates it, and result is:
N 48°44.120 E 019°08.419
Is it possible to do this?
I searched for plugins and solutions, but it's all just for math strings like as "14 + 6".
I am assuming you are working in Java as it is tagged in your question.
You could create a new public class for your GPS coordinates, and store the actual value of the coordinate in the lowest division, which according to your example appears to be minutes or seconds. This allows you to store the value as an int or a double with whatever precision you wish. You could then create a set of private and public methods to complete your mathematical operations and others to display your values in the appropriate fashion:
public class GPSCoordinate {
private double verticalcoord;
private double horizontalcoord;
//Constructors
GPSCoordinate(){
setVertical(0);
setHorizontal(0);
}
GPSCoordinate(double vert, double horiz){
setVertical(vert);
setHorizontal(horiz);
}
//Display methods
public String verticalString(){
return ((int)verticalcoord / 60) + "°" + (verticalcoord - ((int)verticalcoord / 60) *60);
}
public String horizontalString(){
return ((int)horizontalcoord / 60) + "°" + (horizontalcoord - ((int)horizontalcoord / 60) *60);
}
//Setting Methods
public void setVertical(double x){
this.verticalcoord = x;
}
public void setHorizontal(double x){
this.horizontalcoord = x;
}
//Math Methods
public void addMinutesVertical(double x){
this.verticalcoord += x;
}
}
This will allow you to initiate an instance in your main code with a given GPS coordinate, and then you can call your math functions on it.
GPSCoordinate coord1 = new GPSCoordinate(567.23, 245);
coord1.addMinutesVertical(50);
coord1.otherMathFunction(50 * 30);
You will, of course, need to refine the above to make it fit your project. If this isn't helpful, please provide more specifics and I'll see if I can think of anything else that might fit what your looking for.
Can't you just substring the whole thing and search for the expression in the brackets? Then it's just a matter of simple calculation. If I understood the question correctly. The gps data doesn't look like an ordinary expression, so you can't appy math() directly.

Java OOP triangle existence

I have recently started with programming. So far I have learned basics and now its time for OOP and so i have some questions as im building basic programs to just understand principals and link to way I would use it in practical ways.
So I am making simple triangle program in Java, so far it calculates perimeter (later will ad other shapes and other parameters), I hit the wall where I want to add Triangle existence (as side can't be negative) and also Id like to allow user input. Thing is i don't know where to put code and how to refer to class. Linear (non OOP) way it is simple, but how its done in OOP, do i have to make another class or in Triangle class via methods?
my code:
public class Trissturis {
private int sideA, sideB, sideC;
private double perimeter;
public Trissturis(int a, int b, int c) {
sideA = a;
sideB = b;
sideC = c;
}
public double getPerimeter() {
return sideA + sideB + sideC;
}
}
public class TestTri {
public static void main(String[] args) {
Trissturis t1 = new Trissturis(10, 20, 30);
System.out.println("perimeter is " + t1.getPerimeter());
Trissturis t2 = new Trissturis(-1, 20, 30);
}
}
To validate the triangle you have to check that all sides have a length greater than zero, and that no side is longer than the sum of the other two. An method that would accomplish this is:
public boolean isValid(){
return (sideA>0)&&(sideB>0)&&(sideC>0)&&(sideA+sideB>sideC)&&(sideA+sideC>sideB)&&(sideC+sideB>sideA);
}
For the user to input values, it is better to have separate user-interface classes. If this will be a desktop application, you could use some of the Swing classes, for example (although there are alternatives).
interface TriangleFactory {
Triangle create();
}
class ConsoleTriangleFactory implements TriangleFactory {
#Override
Triangle create() {
// read perimeter from console here with some nice prompt
// check that every side is > 0,
// if it's not a number or less than 0 - then do some alert
}
}
Your code to check that the triangle is constructed correctly (with non-negative values, etc) belongs in the Triangle class.
Code to take user input can go in main() in your Test for a small program, but could go in a separate UI namespace for a larger application.
hth

Categories

Resources