First off sorry about the title I could not think how I should title this. The prompt of the assignment had us calculate the volume and surface area of a pyramid and prism with three different classes(two classes with constructors and one test class), and as the title states I keep getting zero.
Here is the prism class:
public class Prism
{
double l;
double w;
double h;
public Prism(double intL, double intW, double intH)
{
double l = intL;
double w = intW;
double h = intH;
}
public double getPrismVolume()
{
return l*w*h;
}
public double getPrismSurfaceArea()
{
return 2*((l*w)+(h*l)+(h*w));
}
}
Here is my Pyramid class:
public class Pyramid
{
double b;
double h;
public Pyramid(double intB, double intH)
{
double b = intB;
double h = intH;
}
public double getPyramidVolume()
{
return (1.0/3.0)*Math.pow(b,2)*h;
}
public double getPyramidSurfaceArea()
{
return Math.pow(b,2)+(2*b*h);
}
}
Here is my test class:
import java.util.*;
public class GeometryTest
{
public static void main(String[] args)
{
Scanner myScanner = new Scanner(System.in);
System.out.print("Enter the length of the prism: ");
String answer1 = myScanner.nextLine();
double length = Double.parseDouble(answer1);
System.out.print("Enter the width of the prism: ");
String answer2 = myScanner.nextLine();
double width = Double.parseDouble(answer2);
System.out.print("Enter the height of the prism: ");
String answer3 = myScanner.nextLine();
double height = Double.parseDouble(answer3);
System.out.print("Enter the pyramid's base: ");
String answer4 = myScanner.nextLine();
double base = Double.parseDouble(answer4);
System.out.print("Enter the pyramid's height: ");
String answer5 = myScanner.nextLine();
double pyramidHeight = Double.parseDouble(answer5);
Pyramid aPyramid = new Pyramid(base,pyramidHeight);
Prism aPrism = new Prism(length,width,height);
System.out.println("The prism's volume is: " + aPrism.getPrismVolume());
System.out.println("The prism's surface area is: " + aPrism.getPrismSurfaceArea());
System.out.println("The pyramid's volume is: " + aPyramid.getPyramidVolume());
System.out.println("The pyramid's surface area is: " + aPyramid.getPyramidSurfaceArea());
}
}
Your constructors are declaring local variables and ignoring the instance variables. The instance variables are left uninitialized, so Java initializes them to their default value, 0.
E.g. change
double l = intL;
to
l = intL;
so l will resolve to the instance variable name.
You are hiding your class level fields with variable shadows;
public Prism(double intL, double intW, double intH)
{
// double l = intL;
// double w = intW;
// double h = intH;
this.l = intL;
this.w = intW;
this.h = intH;
}
and the same problem in Pyramid -
public Pyramid(double intB, double intH)
{
// double b = intB;
// double h = intH;
this.b = intB;
this.h = intH;
}
Related
I am new Java programmer. I am writing simple program to calculate area of the rectangle.You get to input the width and height of the rectangle, but issue is whatever values I enter, the area value is always returning zero. How can i fix this issue. Please have look at my cde.
import java.util.Scanner;
public class Shape {
private int area;
private int width;
private int length;
private String name;
public String shapeName() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter shape name: ");
String name = scanner.nextLine();
return name;
}
public int area() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter width: ");
String width = scanner.nextLine();
System.out.print("Enter height: ");
String height = scanner.nextLine();
return this.width * this.length;
}
}
public class Example1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Shape shape = new Shape();
System.out.println("Shape is " + shape.shapeName());
System.out.println("It's area is " + shape.area());
}
}
Thanks... have a great day! :)
Your problem is that you are not assigning the input to your class variables:
private int width;
private int length;
But to your method local variables String width and String length.
So the line return this.width * this.length; will return 0 because both this.width and this.length weren't changed so they are 0 because in Java int is by default initialized to 0.
You should assign the input to your class variables.
public int area() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter width: ");
width = scanner.nextInt();
System.out.print("Enter height: ");
length = scanner.nextInt();
return width * length;
}
Note:
Use Scanner.nextInt() to get int values instead of Scanner.nextLine() which will return a String, otherwise you should parse these Strings back to int.
String width = scanner.nextLine();
System.out.print("Enter height: ");
String height = scanner.nextLine();
return this.width * this.length;
}
Here you are putting the width in two locals variables, and the return the mul of the property width and height, that are different variables. Try with
this.width = scanner.nextInt();
System.out.print("Enter height: ");
this.height = scanner.nextInt();
return this.width * this.length;
This should fix your problem bro!
public int area() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter width: ");
int width = Integer.parseInt(scanner.nextLine());
this.width = width;
System.out.print("Enter height: ");
int height = Integer.parseInt(scanner.nextLine());
this.height = height;
return this.width * this.length;
}
Assigning value to local new variable means,
this.width and this.length is not used and hence returning 0
public int area() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter width: ");
this.width = scanner.nextInt();
System.out.print("Enter height: ");
this.height = scanner.nextInt();
return this.width * this.length;
}
Do something like this in the class Shape.
You need to initialize global variables width and length using this keyword
class Shape {
private int area;
private int width;
private int length;
private String name;
public String shapeName() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter shape name: ");
String name = scanner.nextLine();
return name;
}
public int area() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter width: ");
int width = scanner.nextInt();
System.out.print("Enter lengtht: ");
int length = scanner.nextInt();
this.width = width;
this.length=length;
return this.width * this.length;
}
}
Use this code also
public double area(){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter width: ");
int width = scanner.nextInt();
System.out.print("Enter height: ");
int height = scanner.nextInt();
double d=width*height;
return d;
}
I'm new to java and I'm trying to write a program that converts Celsius to Fahrenheit
import java.util.Scanner;
public class Temps
{
public static void main(String[] args)
{
System.out.print("Enter temp(70 f or 20 c): ");
double temp = keyboard.nextDouble();
String units = keyboard.next();
if (units.equal("f"))
newtemp = ftoc(temp);
else if (units.equals("c"))
newtemp = ctof(temp);
else System.err.println("units must be c or f");
}
public static double ftoc (int c)
return (( 5.0 / 9.0) * (c - 32));
}
public static double ctof (int f)
{
return ((9.0/5.0)* f+32);
}
}
can someone explain to me what I did wrong.
Quite a few problems
see comments in fixed code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter temp(70 f or 20 c): ");
double temp = keyboard.nextDouble();
String units = keyboard.next();
double newtemp = -1; // not declared
if (units.equals("f")) // should be equals
newtemp = ftoc(temp);
else if (units.equals("c"))
newtemp = ctof(temp);
else System.err.println("units must be c or f");
System.out.println("the new temp is " + newtemp); // need to print it out
}
public static double ftoc (double c) { // take a double
return (( 5.0 / 9.0) * (c - 32));
}
public static double ctof (double f) // take a double
{
return ((9.0/5.0)* f+32);
}
class TestShapes {
public static void main(String[] args){
Scanner input = new Scanner(System.in); // creates the scanner class
System.out.print("Enter the numer of shapes: "); // asks user for input
int N = input.nextInt(); // stores the user input as N
Shape [] myShape = new Shape[N]; // will create as many shapes (N) in an array
for(int i=0;i<N;i++)
{
System.out.println("Enter the choice (Square, Rectangle, Circle):");
int select = input.nextInt();
if(select == 1)
{
//user wanted a Square
System.out.print("Enter the color: ");
String c = input.next();
System.out.print("Enter the side length of the square: ");
double s = input.nextDouble();
myShape[i] = new Square(c,s);
}
else if(select == 2)
{
//user wanted a Rectangle
System.out.print("Enter the color: ");
String c = input.next();
System.out.print("Enter the length of the rectangle: ");
double l = input.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double w = input.nextDouble();
myShape[i] = new Rectangle(c,l,w);
}
else if(select == 3)
{
//user wanted a Circle
System.out.print("Enter the color: ");
String c = input.next();
System.out.print("Enter the radius of the circle: ");
double r = input.nextDouble();
myShape[i] = new Circle(c,r);
}
}
for(int i=0;i<N;i++) //this will print the details
{
System.out.println("\nShape "+ (i+1)+ ":");
myShape[i].print();
}
}
}
class Shape {
String color;
double area;
public Shape(){ // default constructor
color = "red";
}
public Shape(String c){ // constructor
color =c;
}
public String getColor(){ //accessors
return color;
}
public void setColor(String c){//mutators
color=c;
}
//print method
public void print()
{
System.out.println("Color: "+ getColor());
}
public double area(){
return area;
}
}
class Square extends Shape{ // inherits from the shape class
double sideLength;
public Square(){//default constructor
super();
sideLength = 1;
}
public Square(String c, double s){ //constructor
super(c);
sideLength = s;
}
public double getSideLength(){//accessor
return sideLength;
}
public void setSideLength(double s){//mutator
sideLength = s;
}
public double area(){
return sideLength * sideLength; //calculates the area of the square
}
public void print()
{
super.print();
System.out.println("Side length: " + getSideLength()
+ "\nArea: " + area);
}
}
class Rectangle extends Shape{// inherits from the shape class
double length;
double width;
public Rectangle(){//default constructor
super();
length = 1;
width = 1;
}
public Rectangle(String c, double l, double w){ //constructor
super(c);
length = l;
width = w;
}
public double getLength(){//accessor
return length;
}
public double getWidth(){//accessor
return width;
}
public void setLength(double l){//mutator
length = l;
}
public void setSideLength(double w){//mutator
width = w;
}
public double area(){
return length * width; //calculates thea area of the rectangle
}
public void print()
{ // prints out the information
super.print();
System.out.println("Length: " + getLength() + "\nWidth:"+ getWidth() + "\nArea: "+ area);
}
}
class Circle extends Shape{// inherits from the shape class
double radius;
public Circle(String c, double r){//default constructor
super(c);
radius = 1;
}
public Circle(double r){ //constructor
super();
radius = r;
}
public double getRadius(){//accessor
return radius;
}
public void setRadius(double r){//mutator
radius = r;
}
public void print()
{ // prints out the information
super.print();
System.out.println("Radius: " + getRadius() + "\nArea:"+ area);
}
public double area(){
return 3.14159 * (radius * radius); //calculates the area of the circle
}
}
I have tried every which way to get the Area to return and no matter what I try it will not. Everything else works fine, it prints out everything correctly but not the area. any advice?
Enter the number of shapes: 1
Enter the choice (Square, Rectangle, Circle):
1
Enter the color: red
Enter the side length of the square: 2
Shape 1:
Color: red
Side length: 2.0
Area: 0.0
You are not calculating the area , you should use area() in your print statment
System.out.println("Side length: " + getSideLength() + "\nArea: " + area());
You are printing out uninitialized variable area instead of calling the function area().
System.out.println("Side length: " + getSideLength() + "\nArea: " + area());
That should work, but you should avoid using functions and variables of the same name. getArea() would be a better function name.
I am trying to find the area using this formula, however, variables a, b, and c are not initialized. How do I initialize them and let them be used with the scanner?
import java.text.DecimalFormat;
import java.util.Scanner;
public class PA2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat ("0.##");
float a, b, c;
float s = (a + b + c);
float pt1, pt2, pt3, pt4, pt5, pt6;
double Area;
pt1 = (s - a);
pt2 = (s - b);
pt3 = (s - c);
pt4 = (s * pt1);
pt5 = (pt4 * pt2);
pt6 = (pt5 * pt3);
Area = Math.sqrt(pt6);
System.out.println("Enter first side: ");
a = scan.nextFloat();
System.out.println("Enter second side: ");
b = scan.nextFloat();
System.out.println("Enter third side: ");
c = scan.nextFloat();
System.out.println("Your area is: " + fmt.format(Area));
}
}
It is a good practice to define in the paper the order and the algorithm before you start to write the code...
your approach is not so bad, just order the sequence in the code:
Scanner scan = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat ("0.##");
//1. delcare the variables and initialize it...
float a = 0f;
float b = 0f;
float c = 0f;
//2. get the input
System.out.println("Enter first side: ");
a = scan.nextFloat();
System.out.println("Enter second side: ");
b = scan.nextFloat();
System.out.println("Enter third side: ");
c = scan.nextFloat();
//3. Do the Math behind the scenes
float s = (a + b + c);
float pt1, pt2, pt3, pt4, pt5, pt6;
double Area;
pt1 = (s - a);
pt2 = (s - b);
pt3 = (s - c);
pt4 = (s * pt1);
pt5 = (pt4 * pt2);
pt6 = (pt5 * pt3);
Area = Math.sqrt(pt6);
//4. Print the results....
System.out.println("Your area is: " + fmt.format(Area));
Just make it so that instead of just
float a, b, c;
it's:
float a=0;
float b=0;
float c=0;
Which initializes the variables. I had the same issue with another program. Hope this helps.
I'm having two issues in this code where I'm getting and a lossy conversion error
for double to int. No idea how to approach that. (code directly below following lines)
and My average or mean finder keeps giving me incorrect answers when I input numbers with decimals. Any help would be greatly appreciated.
public static double findMaxNumber(double maxNumber, double [] profit) {
double theLowestValue = profit[maxNumber];
import java.util.Arrays;
import java.util.Scanner;
class Business
{
public static void main(String[] args) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("Welcome to the profit-calculation program.");
System.out.println("how many days of data do you have?");
int n = Integer.parseInt (inputScanner.nextLine());
//call upon a function to store the profits into an array for further use.
double[] dayProfitList = inputProfit(n);
//call upon a function to calculate average profit
double averageValue = calcAverageProfit(dayProfitList);
System.out.println("the average of these values is " +calcAverageProfit(dayProfitList) + "."); //print out devised average
//call upon a function to calculate standard devation
double standardDeviation = calcStandardDeviation(averageValue, dayProfitList);
System.out.println("the standard deviation is plus or minus " +calcStandardDeviation(averageValue, dayProfitList));
//find the most profitable day
double theMax = findMax(dayProfitList);
System.out.println("the most profitable day was " + findMax(dayProfitList));
findMaxNumber(theMax, dayProfitList);
System.out.println("and the value earned that day was " + findMaxNumber(theMax, dayProfitList));
findLeast(dayProfitList);
System.out.println("the least profitiable day was " + findLeast(dayProfitList));
}
//function to store each days profits within an array
public static double[] inputProfit(int days) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("input the profit on..");
double[] profits = new double [days+1];
for(int i = 1; i<days + 1; i++) {
System.out.println("day " + i + "?");
double storedDays = Double.parseDouble (inputScanner.nextLine());
profits[i] = storedDays;
}
return profits;
}
//fuction to calculate the profit of said days.
public static double calcAverageProfit(double [] profit){
double sum = 0;
double average = 0;
for(int i = 1; i<profit.length; i++){
sum = profit[i] + sum;
}
average = sum/profit.length;
return average;
}
public static double calcStandardDeviation(double average, double[] profit){
double stepThree = 0;
double sum = 0;
double product = 0;
for(int i = 1;i<profit.length; i++) {
sum = profit[i] - average;
product = sum * sum;
stepThree = product + stepThree;
}
double standardDeviation = stepThree/profit.length;
java.lang.Math.sqrt(standardDeviation);
return standardDeviation;
}
public static double findLeast(double [] profit){
double least = profit[0];
for (int i = 1; i<profit.length; i++) {
if (profit[i]>least)
least = profit[i]; }
return least;
}
public static double findMaxNumber(double maxNumber, double [] profit) {
int MaxNumberInt = (int) maxNumber;
double theLowestValue = profit[maxNumber];
return theLowestValue; }
For fix double to int conversion error, you have to change your code as below.
from
double theLowestValue = profit[maxNumber];
to
double theLowestValue = profit[MaxNumberInt];
After changed, it should below as below.
public static double findMaxNumber(double maxNumber, double[] profit) {
int MaxNumberInt = (int) maxNumber;
double theLowestValue = profit[MaxNumberInt];
return theLowestValue;
}
In your average/mean finder iterate profit[] array from 0th index.
public static double calcAverageProfit(double [] profit) {
...
for (int i = 0; i < profit.length; i++) {
...
}
}