Why does my setLength/getLength and setWidth/getWidth not work - java

My setLength/getLength and setWidth/getWidth do not work. Apparently it's because it cannot find the symbol but I do not know what it means by this.
I tried everything it just seems not to work no matter how hard I try
package practice;
import java.util.Scanner;
public class Oval {
private double width;
private double length;
public static void main(String[] args) {
Oval oval = new Oval();
oval.setLength(102.13);
System.out.println("the circle's length is: " + oval.getLength());
oval.setWidth(211.02);
System.out.printf("The circle's width is: " + oval.getWidth());
String str = "Given the length %, .4f and the width %, .4f,\n\t " + "the circle's area is %,.4f sq.ft\n";
System.out.printf(str, oval.getLength(), oval.getWidth, oval.getArea());
}
}

It seems that you need to create separate methods for the actual get/set methods, as you only have the main method. Perhaps you can do something outside of the main method, like this:
public double getLength(){
return length;
}
public void setLength(double length){
this.length = length;
}
public double getWidth(){
return width;
}
public void setLength(double width){
this.width = width;
}

Related

I can't seem to figure out why I keep getting true when I clearly overridden the equality method

I'm trying to figure this out but I can't seem to get it to compare correctly.
As I try to setup the code whenever I run it the result would end up becoming True when I need it to produce a false test as well. Extensive testing shows it to be always true and I have no idea how to produce a false on it.
import java.util.Scanner;
public class LandTract
{
// instance variables
private static double length , width, area;
/**
* Constructor for objects of class LandTract
*/
public LandTract(double length, double width, double area)
{
// initialise instance variables
length = 0;
width = 0;
}
public LandTract(double length, double width)
{
this.length = length;
this.width = width;
}
public void setLength(double length)
{
this.length = length;
}
public double getLength()
{
return length;
}
public void setWidth(double width)
{
this.width = width;
}
public double getWidth()
{
return width;
}
public double getArea()
{
return area = length * width;
}
public String toString()
{
String str = "Length: " + length + "\nWidth: " + width;
return str;
}
public boolean equals(Object obj)
{
LandTract land = (LandTract) obj;
if (this.length != land.length)
return false;
if (this.width != land.width)
return false;
if (this.area != land.area)
return false;
return true;
}
public static void main(String[] args)
{
Scanner key = new Scanner(System.in);
System.out.print("Enter the length of the first tract of land: ");
length = key.nextDouble();
key.nextLine();
System.out.print("Enter the width of the first tract of land: ");
width = key.nextDouble();
key.nextLine();
LandTract land1 = new LandTract(length , width);
System.out.println("The area of the first tract of land is " + land1.getArea());
System.out.println();
System.out.print("Enter the length of the second tract of land: ");
length = key.nextDouble();
key.nextLine();
System.out.print("Enter the width of the second tract of land: ");
width = key.nextDouble();
key.nextLine();
LandTract land2 = new LandTract(length, width);
System.out.println("The area of the second tract of land is " + land2.getArea());
System.out.println();
if (land1.equals(land2))
System.out.println("Both tracts of land are the same size.");
else
System.out.println("They are different sizes.");
}
}
The best example for a confusing & ironically erroneous comment:
// instance variables
private static double length , width, area;
The program works much better, when you:
(Really) Introduce instance variables:
private double length , width, area;
Fix compiler problems in main method (by declaring local variables with the same identifier ..no good style but quick):
public static void main(String[] args) {
double length, width;
// ...
}
The problem here is that the values being compared (length, width, and area) are static fields, not instance fields. This means that any reference to them will use the same global value, regardless of which instance of the class is referencing them.
Of particular relevance, this.length != land.length in the equals method will always return true, since both this.length and land.length will refer to the same value. (Note that this guarantee is no longer true if multiple threads are involved, but that's not the case with this example.)
This also means that any call to a constructor or a setter will set the shared static fields, overwriting the value previously written when calling a setter or constructor on another instance. For instance, the length, width constructor will overwrite the static length & width fields, and the setLength method will overwrite the static length field.
public LandTract(double length, double width)
{
this.length = length;
this.width = width;
}
public void setLength(double length)
{
this.length = length;
}
The fix is to change these fields to instance fields, rather than static ones:
public class LandTract
{
private double length, width, area;
// [...]
}

How do I implement VarArgs using inheritance?

I am given a class PolyShape represents polygons by their number of sides and an array that contains their side lengths and I have to extend it into a class called quadrilateral that represents a polygon with 4 sides. I am unsure of how to approach this as. I started the program but could someone help me explain what I am supposed to include in terms of arrays and how I should use VarArgs in this case?
import java.util.Arrays;
public class PolyShape {
private int numSides;
private int[] sideLengths;
public PolyShape(int ... sideLengths) {
this.sideLengths = sideLengths;
this.numSides = sideLengths.length;
}
public int getNumSides() {
return numSides;
}
public int[] getSideLengths() {
return Arrays.copyOf(sideLengths, sideLengths.length);
}
public int getPerimeter() {
int perim = 0;
for(int n : sideLengths)
perim += n;
return perim;
}
public String toString() {
String s = "I am a shape with " + numSides + " sides of length: ";
for(int length : sideLengths)
s += length + " ";
s += "\nI am a polygon.";
return s;
}
}
Quadrilateral class:
public class Quadrilateral extends PolyShape {
private final int POLYGON_SIDES = 4;
public Quadrilateral(int ... sideLengths) {
super(sideLengths);
}
public String toString() {
String parentString = super.toString();
parentString += "\nI am a Quadrilateral.";
return parentString;
}
}
You child class is Quadrilateral and it has 4 sides so you don't need to create constructor with vararg method argument. just pass 4 sides inside constructor. Passing those 4 sides to parent constructors will definitely call parent constructor with vararg argument.
public Quadrilateral extends PolyShape {
public Quadrilateral(int side1, int side2, int side3, int side4) {
super(side1, side2, side3, side4);
}
}

Rectangle Class Java

Ok this is homework. I can't for life of me figure out what I am doing wrong here. From the book "The set methods should verify that length and width are each floating-point numbers larger than 0.0 and less than 20.0" I thought I had it but when I run my test it just gives me the area and perimeter.
public class Rectangle {
private float width = 1;
private float length = 1;
public Rectangle(float userWidth, float userLength) {
width = userWidth;
length = userLength;
}
public void setWidth(float userWidth) {
if (userWidth < 0.0 || userWidth > 20.0) {
throw new IllegalArgumentException(Float.toString(width));
} else {
width = userWidth;
}
}
public float getWidth() {
return width;
}
public void setLength(float userLength) {
if (userLength < 0.0 || userLength > 20.0) {
throw new IllegalArgumentException(Float.toString(length));
} else {
length = userLength;
}
}
public float getLength() {
return length;
}
public float calcArea() {
return length * width;
}
public float calcPerimeter() {
return length + length + width + width;
}
}
And my test code is
import java.util.Scanner;
public class RectangleTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Enter the width");
float width = input.nextFloat();
System.out.println("Enter the length");
float length = input.nextFloat();
Rectangle myRectangle = new Rectangle(width, length);
System.out.printf("The area is: %.2f\n", myRectangle.calcArea());
System.out.printf("The perimeter is: %.2f\n",
myRectangle.calcPerimeter());
input.close();
}
}
When you use your Rectangle(float, float) constructor you aren't using your mutator methods to perform validation. You could do something like
public Rectangle(float userWidth, float userLength) {
// width = userWidth;
// length = userLength;
setWidth(userWidth);
setLength(userLength);
}
which would invoke your "setters". Also, there is a subtle (and only potential) bug hiding in
input.close();
because System.in is a global variable you might experience unexpected behavior if you extract your code into a method (and then attempt to read from System.in anywhere else).
You should look here :
public Rectangle(float userWidth, float userLength) {
width = userWidth;
length = userLength;
}
The values have been assigned without verifying. May be use your set method here in constructor. This will throw an exception when you are assigning illegal arguments.

"new way for loop" in Java, not working, suggestion?

this is my problem:
I was trying to use the new for loop in java to print out some strings with doubles. When i compile the code, no errors, but no output, it's like if the for loop isn't working, any help?
the loop it's right in the end, i've printed all the code just to be sure.
abstract class Figure3D {
private float[] center;
protected void setCenter(float[] center){this.center = center;}
public abstract double calcolateVolumn();
protected abstract String figureType();
public void printVolumn(){
System.out.println("Volumn "+ figureType() + calcolateVolumn());
}
}
class Cube extends Figure3D{
private float side;
public Cube(float side, float[] center){
this.side = side;
setCenter(center);
}
#Override
protected String figureType(){
return "Cube ";
}
#Override
public double calcolateVolumn(){
return side*side*side;
}
}
class Sphere extends Figure3D {
private float radius;
public Sphere(float radius, float[] center){
this.radius = radius;
setCenter(center);
}
protected String figureType(){return "Sphere ";}
public double calcolateVolumn(){return ((4f/3f)*radius*radius*radius*3.14f);}
}
import java.util.ArrayList;
import java.util.List;
class TridimensionalFigures {
public static void main(String[] args) {
List<Figure3D> figures3d = new ArrayList<>(10);
Sphere sphere;
Cube cube;
for (int i = 0; i < figures3d.size(); i++) {
sphere = new Sphere(i, new float[] {i, i, i});
figures3d.add(i, sphere);
i++;
cube = new Cube(i, new float[] {i, i, i});
}
//TOFIX: it needs to print out the volums of all the objects in the arraylist
for (Figure3D figures : figures3d) {
System.out.printf("The volumns is: %s %n", figures.calcolateVolumn());
}
}
}
figures3d.size() is 0, so you are not adding anything to the list.
Try changing
for (int i = 0; i < figures3d.size(); i++) {
to
for (int i = 0; i < 10; i++) {
The problem is, the list is never actually populated.
You set it's initial capacity using the constructor, but that doesn't change the size; it just prevents reallocations later.
Because the size is 0, the populizing loop never runs, so the second loop (in question) is skipped due to the list being empty.
Instead of using the list's size to control the populating loop, extract the magic 10 into its own variable, and loop while i < tenVariable.

Java inheritance how to take user input and pass it to sub-sub class?

This is my first ever post here so bear with me please! I have a program that I need to write. Here are the instructions: create a class called areaExcersice in that class you will have a super class called shapes then below it twoDimensionalShapes followed by sub sub class circle and square under the twoDimensionalShapes. In circle extends twoDimensionalShapes, I will pass the user input of radius for example:
System.out.print("what is the radius");
and then
radius = input.nextDouble()
already know how to create and assign classes in a hierarchy system, however, I have no idea how I'm gonna call my circle class under the twiDimensionalShapes. I have to create an if statement so the user can select which shape to choose so something like this "press 1 for circle or 2 for square" and on my
if(user_input == 1){
Here is my question how would I call circle class under twodDimensionalShapes to find the area and pass on radius? Thanks this is all i need to know please if you can just point me out in the good direction i already have created an instance for ex
Circle c = new Circle
Then in my if statement i would do c.getArea() but then where would I put my radius that is asked from the user?
One of my pet peeves with these kinds of projects is they explicitly ask you to create classes when there is no need for them. This only confuses students who can't figure out why they're doing something because there really isn't a reason to do it. You've given no reason to have a Shape class. In the real world I'd take that as an excuse to get rid of it. Since you're required to have one I'm inventing a reason for it to exist: color. This way you can see what Shape might be useful for. If you say "I don't need color" I say "you don't need Shape". See how that works?
I'm using a dirty little trick here called static inner classes so this all works in one file. If you copy this at least take the static of the classes and move them into their own files.
import java.util.Scanner;
public class AreaExcersice {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Choose 1 for circle or 2 for square:");
int userInput = Integer.parseInt( input.nextLine() );
TwoDimensionalShape twoDShape = null;
if (userInput == 1) {
System.out.println("Enter a radius for circle:");
int radius = Integer.parseInt( input.nextLine() );
twoDShape = new Circle("Blue", radius, radius, radius);
} else if (userInput == 2) {
System.out.println("Enter a length for the sides of the square");
int side = Integer.parseInt( input.nextLine() );
twoDShape = new Rectange("Green", 0, 0, side, side);
} else {
System.out.println("Invalid input.");
}
if (twoDShape != null) {
System.out.println( twoDShape.toString() );
}
}
public static abstract class Shape {
String color;
public Shape(String color) {
this.color = color;
}
public abstract String toString();
}
public static abstract class TwoDimensionalShape extends Shape {
int x;
int y;
public TwoDimensionalShape(String color, int x, int y) {
super(color);
this.x = x;
this.y = y;
}
public abstract double getArea();
}
public static class Circle extends TwoDimensionalShape {
int radius;
public Circle(String color, int x, int y, int radius) {
super(color, x, y);
this.radius = radius;
}
#Override
public double getArea() {
return Math.PI * Math.pow(radius, 2);
}
#Override
public String toString() {
return color + " circle at " + x + ", " + y + " with radius " +
radius + " and area of " + getArea();
}
}
public static class Rectange extends TwoDimensionalShape {
int height;
int width;
public Rectange(String color, int x, int y, int height, int width) {
super(color, x, y);
this.height = height;
this.width = width;
}
#Override
public double getArea() {
return width * height;
}
#Override
public String toString() {
return color + " rectange at " + x + ", " + y + " with height " +
height + ", width " + width + " and area of " + getArea();
}
}
}
Displays:
Choose 1 for circle or 2 for square:
1
Enter a radius for circle:
20
Blue circle at 20, 20 with radius 20 and area of 1256.6370614359173
This maybe overkill but it should be clearly showing you what an inheritance structure can do for you. Each class only has implementation code particular to it. Nothing is duplicated. Instead it's shared. Any questions?
You could move anything that's common amongst all of your Shape or TwoDimensionalShape subclasses so that they can be referenced generically:
public abstract class Shape<T extends TwoDimensionalShape> {
public abstract String getName(); // Get the name of the shape for display purposes
public abstract double getArea(); // Get the surface area of this Shape
}
public abstract class TwoDimensionalShape<T extends TwoDimensionalShape> extends Shape<T> {
private double area = 0;
public double getArea() {
return this.area;
}
protected void setArea(double area) {
this.area = area;
}
}
public class Circle extends TwoDimensionalShape<Circle> {
public Circle ( double radius ) {
setArea( Math.PI * Math.pow(radius, 2) );
}
public String getName() {
return "Circle";
}
}
public class Square extends TwoDimensionalShape<Square> {
public Square ( double width, double height ) {
setArea( width * height );
}
public String getName() {
return "Square";
}
}
So the point of having TwoDimensionalShapes is a bit obscure, but we can guess that it defines methods like "getArea()" without implementing them. Each class that extends TwoDimensionalShapes has to implement its own area calculation.
I don't think things like "setArea(double area)" are very useful; areas are not so difficult to calculate that we need to store them, and storing them causes other problems.
So we end up with something like these:
public TwoDShape extends Shape // I have no use for Shape in this example...
{
public double getArea(); // this is an abstract method, hope you've covered those.
}
public Circle extends TwoDShape
{
private double radius;
public Cirlcle(double givenRadius) { radius = givenRadius; }
public double getArea() { return PI*radius*radius; }
}
I've left out a great deal. The getArea() should insure the radius is not 0 and do something like throw an exception if it is, for instance.
Now, to use this, you might have:
public class Main
{
public static void main(String ... arguments)
{
Circle c = new Circle(4.0);
System.out.println("Radius of 4 gives area of " + c.getArea();
}
}
Now, I'll leave Square to you to do, it will be quite similar to Circle. Let us know how it goes. After you've done Square, you'll be able to do something like:
public Main
{
public static void main(String ... arguments)
{
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(4.0);
shapes[1] = new Square(5.0);
shapes[2] = new Square(6.0);
for (shape : shapes)
{
System.out.println("Area is " + shape.getArea());
}
}
}
Thanks guys! You guys are all awesome!! I have not yet covered abstract classes but your explicit code showed me the way! Something clicked on me and alas! i saw the light beaming across the room! I idolize you programmers as well as admire you because someday i will become a professional just like you guys. I am striving to achieve deep knowledge within the programming field and this is just the start. Again thank you so much for clearing my head and pointing me in the right direction! It feels so good to complete a program on your own and have it output correctly and thanks Stack Overflow and all its respective members!I am a noob and first time posting here so i might get down voted for answering in an incorrect format.

Categories

Resources