Testing my program? - java

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.

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;
// [...]
}

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.

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

Calling an object from different classes

I have a main class to run a BMI calculator class which calculates BMI info (body mass index) with fields for name, age, sex, height, and weight.
There is also a WaistToHip calculator class to calculate waist-to-hip ratio with fields
waist and hip.
However, when I wanted to create a
BodyFat calculator I need the height and waist from both classes.
How am I suppose to call these in my body fat calculator class for my formula?
public class body_fat_calculation {
private double neck;
private double CBF;
waist_to_hip_ratio waist;
bmiCalculator height;
public body_fat_calculation(double neck) {
super();
this.neck = neck;
}
public double getCBF() {
return CBF;
}
public void setCBF(double cBF) {
CBF = cBF;
}
public double getNeck() {
return neck;
}
public void setNeck(double neck) {
this.neck = neck;
}
public double Round(double Rval, int Rpl){
double p = Math.pow(10, Rpl);
Rval=Rval*p;
double tmp = Math.round(Rval);
return tmp/p;
}
public void calculateWTHR(){
CBF= Round((495/(1.0324 - 0.19077 * Math.log10((waist)-(neck)) + 0.15456 * Math.log10(height)) - 450),2);
}
}
Why don't you do something like this? If you notice I have added two parameters to the BodyFatCalculator class - waist and height.
public class Main {
public static void main(string[] args){
// I assume you will want to use a scanner to get user input to set these variables dynamically
// for the sake of the example, I have set them myself.
double height = 1.82; // meters
double weight = 170.0;
double waist = 35.0;
double hip = 40.0;
double neck = 7.1;
String name = "Dave";
String sex = "M";
int age = 20;
// create new BMI Calculator to figure out body mass index
BMICalculator bmiCalc = new BMICalculator(name, age, sex, height, weight);
double bmi = bmiCalc.calculateBmi(); // calculate body mass index
WaistToHipCalculator waistHipCalc = new WaistToHipCalculator(waist, hip);
double whr = waistHipCalc.calculateWhr(); // calculate waist to hip ratio
BodyFatCalculator bfCalc = new BodyFatCalculator(neck, height, waist);
double bf = bfCalc.calculateBf(); // calculate body fat
// print results
}
}
Classes are more nouns. A verb should be a method. With a class called BodyFatCalculation I think you're trying too hard to use a lot of classes. Just have a Body (noun) class with calculateBodyMassIndex and calculateBodyFat (verbs) as methods. You could create a Dimensions class with height and waist in it (with getters and setters as needed) and keep an instance of that inside the Body class, but that's overkill here.

Implementing a Jump Table in Java

How do I make the switch/case statement in this simple Calculator program into a jump table.
import java.lang.*;
import java.util.*;
public class Calculator
{
private int solution;
private static int x, y, ops;
private char operators;
public Calculator()
{
solution = 0;
}
public int addition(int x, int y)
{
return x + y;
}
public int subtraction(int x, int y)
{
return x - y;
}
public int multiplication(int x, int y)
{
return x * y;
}
public int division(int x, int y)
{
solution = x / y;
return solution;
}
public void calc(int ops){
Scanner operands = new Scanner(System.in);
System.out.println("operand 1: ");
x = operands.nextInt();
System.out.println("operand 2: ");
y = operands.nextInt();
System.out.println("Solution: ");
switch(ops)
{
case(1):
System.out.println(addition(x, y));
break;
case(2):
System.out.println(subtraction(x, y));
break;
case(3):
System.out.println(multiplication(x, y));
break;
case(4):
System.out.println(division(x, y));
break;
}
}
public static void main (String[] args)
{
System.out.println("What operation? ('+', '-', '*', '/')");
System.out.println(" Enter 1 for Addition");
System.out.println(" Enter 2 for Subtraction");
System.out.println(" Enter 3 for Multiplication");
System.out.println(" Enter 4 for Division");
Scanner operation = new Scanner(System.in);
ops = operation.nextInt();
Calculator calc = new Calculator();
calc.calc(ops);
}
}
To be completely honest, I don't know exactly what a jump table is (couldn't find any explanations online) so I don't know how it differs from a switch/case statement.
Side Note: This code only deals with integers so if you divide 5/3 its gives you 1. How can I easily change it to take floats/doubles.
As mentioned, a jump table is an array of offsets/pointers to functions. Unlike C/C++, Java doesn't really have function pointers (Function Pointers in Java)
But you can pretend, and do it the object oriented way. Define a base class (Funky) with one method (f). Derive mutiple children, one for each of your functional operations (+,-,*,/, etc), and create a single object for each child (it is just an interface, after all), and store that child into an array of type (Funky).
Lookup the operation in the table, and call the method on your arguments
Example:
Define a base class, (or an interface, which makes you happier?). Note that if you extend a class, you can use the base class method as a default (generate an error message, or throw an exception),
public class X
//or, public interface X
{
//method
Z fun(Z z1, Z z2)
{
//nothing to see here
}
}
class X1 extends X //or, implements X
{
public Z fun(Z z1, Z z2)
{
//variant1 stuff here
}
}
...
public class Xn extends X //or, implements X
{
public Z fun(Z z1, Z z2)
{
//variantn stuff here
}
}
Oh, and you will need instances, and load them into an array (the jumptable).
There are certain techniques which are idiomatic to certain languages, and jumptables are more of a systems thing and less of a Java thing, not really a Java idiom.
well, i don't know what is a jump table, but if you wanna control another type of numbers, you can change of parameter for example you method:
public int addition(int x, int y)
{
return x + y;
}
if you wanna Double-->
public int addition(Double x, Double y)
but i strongly recommend you user the type Number every other class extens from Number.
Number.class
ex:
public static String numeroToLetra(Number num)
{
Integer numero = Integer.valueOf(num.intValue()); //int value
Double numero = Double.valueOf(num.doubleValue());........
}//so you can pass whatever type of number.
This is an old question, but I think it still has value for illustrating what you can do since Java 8. Basically, you create an interface whose sole purpose is to provide a type for an operations array and then you use method references to populate the operations array. After that, you can use the index to select the proper operation. I made minimal modifications to the OP's code such that the comparison is easiest:
import java.util.Scanner;
public class Calculator
{
//
// Create an interface to use as Type for
// operations array.
//
private interface BinaryOperation {
int performOperation(int a, int b);
}
//
// Array has one unused element to make coding easier
// and use operation as a direct index.
// You can replace with 4 element array easily.
//
BinaryOperation[] operations = new BinaryOperation[5];
private int solution;
private static int x, y, ops;
private char operators;
public Calculator()
{
solution = 0;
//
// Initialize jump table using method references.
//
operations[1] = this::addition;
operations[2] = this::subtraction;
operations[3] = this::multiplication;
operations[4] = this::division;
}
public int addition(int x, int y)
{
return x + y;
}
public int subtraction(int x, int y)
{
return x - y;
}
public int multiplication(int x, int y)
{
return x * y;
}
public int division(int x, int y)
{
solution = x / y;
return solution;
}
public void calc(int ops){
Scanner operands = new Scanner(System.in);
System.out.println("operand 1: ");
x = operands.nextInt();
System.out.println("operand 2: ");
y = operands.nextInt();
System.out.println("Solution: ");
//
// Call binary operation through jump table
//
System.out.println(operations[ops].performOperation(x, y));
}
public static void main (String[] args)
{
System.out.println("What operation? ('+', '-', '*', '/')");
System.out.println(" Enter 1 for Addition");
System.out.println(" Enter 2 for Subtraction");
System.out.println(" Enter 3 for Multiplication");
System.out.println(" Enter 4 for Division");
Scanner operation = new Scanner(System.in);
ops = operation.nextInt();
Calculator calc = new Calculator();
calc.calc(ops);
}
}
If you're working with a version of Java that supports lambdas, a solution that is more true to the requirement to implement as a "jump table" would use an actual jump table, one that maps operator codes to lambda expressions that implement each the operands.
This is a pleasing way not only to eliminate clunky switch statements, but to produce more maintainable and more easily extensible code. Future new operands can easily be added later without making any changes to the Calculator implementation. Simply implement the new operator and its naming method, and add it to the jump tables. Your Calculator will automatically support the new operand.
import com.google.common.collect.ImmutableMap;
import java.lang.*;
import java.util.*;
public class Calculator
{
private static final Map<Integer,BinaryOperator<Integer>> evaluators = ImmutableMap.<Integer, BinaryOperator<Integer>>builder()
.put(1, (Integer x, Integer y) -> new IntAddition().evaluateFor(x,y))
.put(2, (Integer x, Integer y) -> new IntSubtraction().evaluateFor(x,y))
.put(3, (Integer x, Integer y) -> new IntMultiplication().evaluateFor(x,y))
.put(4, (Integer x, Integer y) -> new IntDivision().evaluateFor(x,y))
.build();
private static final Map<Integer,Nameable> names = ImmutableMap.<Integer, Nameable>builder()
.put(1, () -> new IntAddition().getName())
.put(2, () -> new IntSubtraction().getName())
.put(3, () -> new IntMultiplication().getName())
.put(4, () -> new IntDivision().getName())
.build();
private int solution;
private static int x, y, ops;
public Calculator()
{
solution = 0;
}
public void calc(int opcode)
{
Scanner operands = new Scanner(System.in);
System.out.println("Enter operand 1: ");
x = operands.nextInt();
System.out.println("Enter operand 2: ");
y = operands.nextInt();
System.out.print("Solution: ");
System.out.println(evaluators.get(opcode).evaluateFor(x, y));
}
public static void main(String[] args)
{
System.out.println("What operation?");
for (Integer opcode : evaluators.keySet())
{
System.out.println(String.format(" Enter %d for %s", opcode, names.get(opcode).getName()));
}
Scanner operation = new Scanner(System.in);
ops = operation.nextInt();
Calculator calc = new Calculator();
calc.calc(ops);
}
interface Nameable
{
String getName();
}
interface BinaryOperator<T>
{
T evaluateFor(T x, T y);
}
static class IntAddition implements BinaryOperator<Integer>, Nameable
{
IntAddition() { }
public Integer evaluateFor(Integer x, Integer y)
{
return x + y;
}
public String getName()
{
return "Addition";
}
}
static class IntSubtraction implements BinaryOperator<Integer>, Nameable
{
IntSubtraction() { }
public Integer evaluateFor(Integer x, Integer y)
{
return x - y;
}
public String getName()
{
return "Subtraction";
}
}
static class IntMultiplication implements BinaryOperator<Integer>, Nameable
{
IntMultiplication() { }
public Integer evaluateFor(Integer x, Integer y)
{
return x * y;
}
public String getName()
{
return "Multiplication";
}
}
static class IntDivision implements BinaryOperator<Integer>, Nameable
{
IntDivision() { }
public Integer evaluateFor(Integer x, Integer y)
{
return x / y;
}
public String getName()
{
return "Division";
}
}
}

Categories

Resources