Rectangle Class Java - 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.

Related

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

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;
}

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 to print out a toString for this class?

I have written a polynomial class and a tester class. The polynomial class can evaluate and return the sum of the polynomial when the degree, coefficients and the value of x are provided. Basically I need to edit my toString method so it actually prints out the polynomial
import java.util.Arrays;
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
private double value;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient)
{
this.coefficient[this.degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public double Evaluate(double value)
{
this.value =value;
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
return sum;
}
/** Standard toString method */
//needed something better than this below...needed an actual polynomial printed out
public String toString()
{
return "The degree of the polynomial is " + degree + " and the value for which it has been evaluated is" + value;
}
}
This should be along the lines you should be proceeding. I included the main function in your Polynomial class for simplicity, so you will have to modify that if you want to keep it in your tester class. Notice that degree has been made into an integer array of size degree +1(allocated in the constructor):
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient, int degree)
{
this.coefficient[degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
}
public double getSum(){
return sum;
}
public String toString()
{
String s = "";
for (int i=0; i <= degree; i++)
{
s += coefficient[i];
switch (i) {
case 0:
s += " + ";
break;
case 1:
s += "x + ";
break;
default:
s += "x^" + i + ((i==degree)?"":" + ");
}
}
return s;
}
public static void main(String[] args) {
int degree;
double sum;
int coefficient;
Scanner key = new Scanner(System.in);
System.out.println("Enter the degree of the polynomial");
degree=key.nextInt();
Polynomial fun = new Polynomial(degree);
fun.Evaluate(3.0);
System.out.println(" The sum of the polynomial is " + fun.getSum());
System.out.println(fun);
}
}
The usual way of making the objects of a class printable is to supply a toString method in the class, which specifies how to express objects of that class as a String. Methods such as println and other ways of outputting a value will call a class's toString method if they need to print an object of that class.
You should adopt the same pattern with your Polynomial class - write a toString method with all the output logic. Then in your PolynomialTester class, all you need to write is System.out.println(fun); and the rest will just happen. You'll find this far more versatile than writing a method that actually does the printing. For example, you'll be able to write something like
System.out.println("My polynomial is " + fun + " and " + fun + " is my polynomial.");
if that's your idea of fun.
A few other things concern me about your class.
You seem to be only storing one coefficient and one exponent. I'd expect a polynomial to have a whole array of coefficients.
You have fields for evaluation and sum - but these only really make sense while a polynomial is being evaluated. They're not long-term properties of the polynomial. So don't store them in fields. Have them as local variables of the evaluate method, and return the result of the evaluation.
I'd expect a class like this to be immutable. That is, you should provide all the coefficients when the object is created, and just never change them thereafter. If you do it that way, there's no need to write setter methods.
So I've written my own version of your class, that fixes those issues listed above, and implements a toString method that you can use for printing it. A second version of toString lets you specify which letter you want to use for x. I've used "varargs" in the constructor, so you can construct your polynomial with a line such as
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
specifying the coefficients from the constant term through in order to the coefficient of the term with the highest exponent. Or you can just pass an array.
See that I've changed the logic a wee bit - my version prints the polynomial in the conventional order, from highest to lowest exponent. It leaves off the decimals if the coefficient is an integer. It doesn't print a 1 in front of an x. And it deals cleanly with - signs.
import java.util.Arrays;
public class Polynomial {
private double[] coefficients;
public Polynomial(double... coefficients) {
this.coefficients = Arrays.copyOf(coefficients, coefficients.length);
}
public int getDegree() {
int biggestExponent = coefficients.length - 1;
while(biggestExponent > 0 && coefficients[biggestExponent] == 0.0) {
biggestExponent--;
}
return biggestExponent;
}
public double getCoefficient(int exponent) {
if (exponent < 0 || exponent > getDegree()) {
return 0.0;
} else {
return coefficients[exponent];
}
}
public double evaluateAt(double x) {
double toReturn = 0.0;
for (int term = 0; term < coefficients.length; term++) {
toReturn += coefficients[term] * Math.pow(x, term);
}
return toReturn;
}
#Override
public String toString() {
return toString('x');
}
public String toString(char variable) {
boolean anythingAppendedYet = false;
StringBuilder toReturn = new StringBuilder();
for (int exponent = coefficients.length - 1; exponent >= 0; exponent--) {
if (coefficients[exponent] != 0.0) {
appendSign(toReturn, exponent, anythingAppendedYet);
appendNumberPart(toReturn, exponent);
appendLetterAndExponent(toReturn, exponent, variable);
anythingAppendedYet = true;
}
}
if (anythingAppendedYet) {
return toReturn.toString();
} else {
return "0";
}
}
private void appendSign(StringBuilder toAppendTo, int exponent, boolean anythingAppendedYet) {
if (coefficients[exponent] < 0) {
toAppendTo.append(" - ");
} else if (anythingAppendedYet) {
toAppendTo.append(" + ");
}
}
private void appendNumberPart(StringBuilder toAppendTo, int exponent) {
double numberPart = Math.abs(coefficients[exponent]);
if (numberPart != 1.0 || exponent == 0) {
//Don't print 1 in front of the letter, but do print 1 if it's the constant term.
if (numberPart == Math.rint(numberPart)) {
// Coefficient is an integer, so don't show decimals
toAppendTo.append((long) numberPart);
} else {
toAppendTo.append(numberPart);
}
}
}
private void appendLetterAndExponent(StringBuilder toAppendTo, int exponent, char variable) {
if (exponent > 0) {
toAppendTo.append(variable);
}
if (exponent > 1) {
toAppendTo.append("^");
toAppendTo.append(exponent);
}
}
}
So I tested it with this class
public class PolynomialTester {
public static void main(String[] args) {
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
System.out.println(fun.getDegree());
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
}
}
and the output was
4
139.0
x^4 + 5x^2 + 2x + 7
then I realised that you wanted to be able to input the coefficients in a loop. So I changed PolynomialTester to this. See how I build the array and then create the object.
import java.util.Scanner;
public class PolynomialTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the degree:");
int degree = input.nextInt();
double[] coefficients = new double[degree + 1];
for( int exponent = 0; exponent <= degree; exponent++) {
System.out.println("Enter the coefficient of x^" + exponent);
coefficients[exponent] = input.nextDouble();
}
Polynomial fun = new Polynomial (coefficients);
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
input.close();
}
}
Note that if you really want your polynomial to be printed in "reverse" order, with the constant term first, you could change the loop in the toString method to this.
for (int exponent = 0; exponent < coefficients.length; exponent++) {
You may add a class member String poly, then modify the following method.
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient= key.nextInt();
evaluation = Math.pow(value, i)*coefficient ;
this.sum += evaluation;
this.poly = "";
if(coefficient != 0)
{
if(i > 0)
{
this.poly += " + " + Integer.toString(coefficient) + "x^" + Integer.toString(i); // you may replace x with the actual value if you want
}
else
{
this.poly = Integer.toString(coefficient)
}
}
}
}

Testing my program?

I already have the class I need to implement in to my code. The instructions are: Code a testing program/class. This should construct or instantiate objects of the class you coded in step #1. Your testing program should call every method to make sure they work. You should construct at least two objects – one with the default constructor and one with the “other” constructor. For the second scenario, ask the user what values for (radius and) height. You may use any input and output that you want for this.
This is what I have so far and I'm stuck:
public class Cube
{
private double height;
public Cube(){
height = 1.0;
}
public Cube(double h){
height = h;
}
public double getHeight(){
return height;
}
public void setHeight(double h){
height = h;
}
public double calcVolume() {
return height*height*height;
}
public double calcSurface(){
return height*height*6;
}
public String toString(){
return this.toString();
}
public boolean equals(Cube c){
return (c.getHeight() == this.height);
}
}
import java.util.*
public class TestTheCube
{
public static void main(String[] args)
{
Cube cube1 = new Cube();
Scanner kb = new Scanner(System.in);
System.out.print("Enter a height as a positive number");
double height = kb.nextDouble();
Cube cube2 = new Cube(height);
System.out.println(
}
}
I've invoked calcVolume() of cube1 and cube2.
Cube cube1 = new Cube();
Scanner kb = new Scanner(System.in);
System.out.print("Enter a height as a positive number");
double height = kb.nextDouble();
Cube cube2 = new Cube(height);
System.out.println("Cube 1's volume = "+cube1.calcVolume());
System.out.println("Cube 2's volume = "+cube2.calcVolume());
.....//repeat for every instance method you have.

Classes and Objects. Getting 0.0 as answer when calculating price. - JAVA

I'm working out a question from a labsheet but i'm only getting 0.0 as answer when running the program. I can't find out what's wrong please help.
The question:
Implement a class Pizza with attribute diameter (in cm), cost_sq_cm (cost per square cm) and area. Its methods are:
• Constructor to create an object of type Pizza with a given diameter and given price_sq_cm.
• Mutator and accessor methods for diameter and cost_sq_cm.
• calcArea to calculate the area of a given pizza.
• getPrice to calculate and return the price of a pizza.
Write a class TestPizza with a main method that declares an object of type Pizza with a user inputted diameter and user-­‐inputted cost_sq_cm of a circular pizza, and display the price of the pizza.
The Pizza class:
package Number3;
public class Pizza {
private int diameter;
private float cost_sq_cm;
private double area;
private double price;
public Pizza() //default constructor
{
diameter = 0;
cost_sq_cm = 0;
area = 0;
price = 0;
}
public Pizza(int d,float cost,double a,double p) //overloaded constructor
{
d = diameter;
cost = cost_sq_cm;
a = area;
p = price;
}
public void Constructor() //method
{
Pizza P = new Pizza();
}
public void setDiameter(int d) //mutator
{
d = diameter;
}
public int getDiameter() //accessor
{
return diameter;
}
public void setCost(float c)
{
c = cost_sq_cm;
}
public float getCost()
{
return cost_sq_cm;
}
public double calcArea()
{
area = 3.142 * (diameter * diameter);
return area;
}
public double getPrice()
{
price = area * cost_sq_cm;
return price;
}
public void display()
{
System.out.print("The area is: "+this.price);
}
}
TestPizza:
package Number3;
import java.util.Scanner;
public class TestPizza {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
float area = 0;
Pizza P = new Pizza();
int d; float c,a = 0;
System.out.print("Enter a value for the diameter: ");
d = input.nextInt();
P.setDiameter(d);
System.out.print("Enter a value for the cost: ");
c = input.nextFloat();
P.setCost(c);
P.display();
}
}
I'm new to JAVA. Please be lenient.
You should multiply cost per square centimeter times area to get price. You'll get zero if either one is equal to zero. I see where you've set diameter, but not area.
You set diameter, but you don't calculate area when you set it.
public void setDiameter(int d) //mutator; lose this comment. worthless clutter.
{
d = diameter;
area = calcArea();
}
I'd recommend following the Java idiom. Don't write a display() method; better to override toString().
I'd write it this way:
package cruft;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* Pizza
* #author Michael
* #link https://stackoverflow.com/questions/28658669/classes-and-objects-getting-0-0-as-answer-when-calculating-price-java
* #since 2/22/2015 12:27 PM
*/
public class Pizza {
private static final int DEFAULT_DIAMETER = 38;
private static final double DEFAULT_COST = 15.0;
private static final double DEFAULT_COST_PER_AREA = 0.013226; // 15 euro for a 38 cm diameter pizza
private static final NumberFormat DEFAULT_FORMAT = new DecimalFormat("#.####");
private final int diameter;
private final double costPerArea;
private final double price;
public static void main(String[] args) {
int diameter = ((args.length > 0) ? Integer.valueOf(args[0]) : DEFAULT_DIAMETER);
double costPerArea = ((args.length > 1) ? Double.valueOf(args[1]) : DEFAULT_COST_PER_AREA);
Pizza pizza = new Pizza(diameter, costPerArea);
System.out.println(pizza);
}
public Pizza(int diameter, double costPerArea) {
if (diameter <= 0) throw new IllegalArgumentException("diameter must be positive");
if (costPerArea <= 0) throw new IllegalArgumentException("cost per area must be positive");
this.diameter = diameter;
this.costPerArea = costPerArea;
this.price = this.costPerArea*this.calculateArea();
}
public double getPrice() {
return price;
}
private double calculateArea() {
return Math.PI*this.diameter*this.diameter/4.0;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Pizza{");
sb.append("diameter=").append(diameter);
sb.append(", costPerArea=").append(DEFAULT_FORMAT.format(costPerArea));
sb.append(", price=").append(NumberFormat.getCurrencyInstance().format(getPrice()));
sb.append('}');
return sb.toString();
}
}
For setting a field or another value it is
variable = value;
so
diameter = d;
It looks like your setCost and setDiameter methods need to be changed,
From
d = diameter;
To
this.diameter = d;
Instead of:
System.out.print("The area is: "+this.price);
Use:
System.out.print("The area is: "+this.getPrice());
You need to calculate area as well. So in your main method call it like:
P.calcArea();//to calculate area
You initialised price as 0, when you called new Pizza() and you never called getPrice which is where you calculate the price.
Also change your setter for cost from:
public void setCost(float c) {
c = cost_sq_cm;
}
To
public void setCost(float c) {
cost_sq_cm = c;
}

Categories

Resources