Calculating perimeter and area of a rectangle - java

I need to be able to input length and width of a rectangle into a console and calculate its perimeter and area. I have it working other than accepting my inputs for the calculations. I know I'm close, but can't seem to figure it out. Thanks in advance for your help. Keep in mind I'm a novice to put it nicely, so your answers may not make sense to me at first. I cannot get it to calculate the values that I input into the console.
package edu.purdue.cnit325_lab1;
public class Rectangle {
private static double length;
private static double width;
public Rectangle() {
length=0.0;
width=0.0;
}
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double FindArea() {
return length*width;
}
public double FindPerim() {
return length*2 + width*2;
}
}
package edu.purdue.cnit325_lab1;
import java.util.Scanner;
public class TestRectangle {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanL = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double L = scanL.nextDouble();
Scanner scanW = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double W = scanW.nextDouble();
//int W = scanW.nextInt();
double RectangleArea;
Rectangle unitRectangle = new Rectangle();
RectangleArea = unitRectangle.FindArea();
System.out.println("The area of a unit rectangle is " + RectangleArea);
double RectanglePermiter;
Rectangle perimRectangle = new Rectangle();
RectanglePermiter = perimRectangle.FindPerim();
System.out.println("The permimiter of the unit rectangle is " + RectanglePermiter);
}
}

Note that you are calling the Rectangle constructore with no arguments thus setting its width and height to zero, you should use
Rectangle unitRectangle = new Rectangle(L,W);
and indeed like the other answer you should use one Scanner instance.
Plus regarding coding style: do not upercase your variable names. Its quite confusing for more "experienced" java developers. :-)

you missed to call parameterized constructor.
public static void main(String[] args) {
Scanner scanL = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double L = scanL.nextDouble();
System.out.print("Please enter the length of the rectangle: ");
double W = scanL.nextDouble();
Rectangle rectangle = new Rectangle(l,w);
double rectangleArea = rectangle .FindArea();
System.out.println("The area of a unit rectangle is " + rectangleArea);
double rectanglePermiter = rectangle.FindPerim();
System.out.println("The permimiter of the unit rectangle is " + rectanglePermiter);
}
Note: Unnecessarily you created two Scanner objects and two Rectangle objects in your code,which are removed from the above code.

Use one Scanner instance. Just reuse it.
Scanner scanner = new Scanner (System.in);
System.out.print("Please enter the length of the rectangle: ");
double L = scanner.nextDouble();
System.out.print("Please enter the length of the rectangle: ");
double W = scanner.nextDouble();
Update: You don't pass the L and W to the constructor as the other answer points out. However, some mistakes you made:
You declared length and width as static. Don't do that. That makes no sense. The length and the width are properties of a rectangle and shouldn't be shared by all rectangle instances.
You don't use the correct naming conventions: variables start with a lowercase character, class names start with an uppercase character.
You are creating two instances of your Rectangle to calculate both perimeter and area of the same rectangle. Share that instance instead.

So you need to set the values in some way... you can do either
A)
Rectangle unitRectangle = new Rectangle(l,w);
B)
or create getters and setters in the rectangle class..
setLength(double l) length = l;
setWidth(double w) width = w
double getLength() return length;
double getWidth() return height;
Since you are initializing with the default constructor
aka
Rectangle unitRectangle = new Rectangle();
the values for length and width will also be zero.

Your code consists of the Default constructor, which will initialize the respective values length and width to 0.0 as set by you and also consist of parametrized constructor which requires input values to be provided and will set the value accordingly.
When you are creating the object of your class, you are calling the Default Constructor instead of parametrized constructor in this line
Rectangle unitRectangle = new Rectangle();
Thus setting them to 0.0
If you do Something like this
Rectangle unitRectangle2 = new Rectangle(2.3,4.3);
This will create the object having values for length and breadth as 2.3 and 4.3 respectively.

//write a java program which will calculate area and perimeter of rectangle by accepting radius from cmd prompt
//area = width x height,perimeter = (2 x width) + (2 x height)
class AreaAndPerOfRect
{
int h,w;
void set(int x,int y)
{
h=x;
w=y;
}
int AreaOfRect()
{
int area=w*h;
return area;
}
int PerOfRect()
{
int per=(2*w)+(2*h);
return per;
}
void disp()
{
int area=AreaOfRect();
System.out.println("area of rectangle"+area);
int per=PerOfRect();
System.out.println("area of rectangle"+per);
}
}
class AreaAndPerOfRectDemo
{
public static void main(String args[])
{
if(args.length!=2)
{
System.out.println("please enter two values");
}
else
{
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
AreaAndPerOfRect ap=new AreaAndPerOfRect();
ap.set(x,y);
ap.disp();
}
}
}

//This is the Java code for finding the area and perimeter of a rectangle
package demo;
import java.util.Scanner;
public class DemoTranslation {
public static int area(int length, int width) {
int areaOfRectangle;
areaOfRectangle = length * width;
System.out.println("Area of Rectangle is : " + areaOfRectangle);
return 0;
}
public static int perimeter(int length, int width) {
int perimeterOfRectangle;
perimeterOfRectangle = (length + width) * 2;
System.out.println("Perimeter of Rectangle is : " + perimeterOfRectangle);
return 0;
}
public static void main(String[] args) {
int length, width, choice;
System.out.println("Enter the length of the triangle ");
length = STDIN_SCANNER.nextInt();
System.out.println("Enter the width of the triangle ");
width = STDIN_SCANNER.nextInt();
System.out.println("Enter 1 : View the area ");
System.out.println("Enter 2 : View the perimeter ");
System.out.println("Enter 3 : view both ");
choice = STDIN_SCANNER.nextInt();
switch(choice) {
case 1:
area(length, width);
break;
case 2:
perimeter(length, width);
break;
case 3:
area(length, width);
perimeter(length, width);
break;
default:
System.out.println("Invalid option ");
break;
}
}
public final static Scanner STDIN_SCANNER = new Scanner(System.in);
}

Related

Why is the output of this polymorphism program shows 0 in this Java program?

I am trying to integrate the topics like Dynamic Polymorphism, Inheritance and switch statements altogether in a single program where, I am getting an output but the result is always 0 in the console window. There is no error too. May be it is a logical error but I am not sure. I am just at the beginning phase of learning Java.
import java.io.IOException;
import java.util.Scanner;
// Dynamic Polymorphism implementation with switch case
public class Main {
public static void main(String[] args) throws IOException{
Shapes myShape = new Shapes();
Shapes myTriangle = new Triangle();
Shapes myCircle = new Circle();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Shape you would like to get the area of: ");
System.out.println("Your Choices are : 1=Triangle, 2= Circle");
int response = scanner.nextInt();
switch(response)
{
case 1 : System.out.println("Enter the base of the triangle: ");
scanner.nextDouble();
System.out.println("Enter the height of the triangle: ");
scanner.nextDouble();
System.out.println(myTriangle.area());
break;
case 2 : System.out.println("Enter the radius of the circle: ");
scanner.nextDouble();
System.out.println(myCircle.area());
break;
default : System.out.println("Invalid Input");
System.out.println(myShape.area());
}
scanner.close();
}
}
class Shapes {
double base;
double height;
double radius;
public double area() {
System.out.println("Formula for Area of triangle is 1/2 * base * height");
System.out.println("Formula for Area of Circle is 3.14 * radius * radius");
return 0;
}
}
class Triangle extends Shapes{
double x = 0.5*base*height;
#Override
public double area() {
System.out.println("Area of Triangle is : ");
return x;
}
}
class Circle extends Shapes{
double y = 3.14*radius*radius;
#Override
public double area() {
System.out.println("Area of Circle is: ");
return y;
}
}
```
You missed to assign value to the base, height, and radius i.e. you missed something like this:
myTriangle.base = scanner.nextDouble();
Secondly, your area() method should compute on the fly. Otherwise, the area value will always be 0, as originally all the base, height, and radios are 0. So for Triangle class, it should be like this:
class Triangle extends Shapes {
#Override
public double area() {
System.out.println("Area of Triangle is : ");
return 0.5 * base * height;
}
}
You should do the same for Circle.

add object directly in a array

I have written a object for a school assignment. now i'm trying to add it to an array so i can add multiple boxes.
my main
String name;
double userInputLength;
double userInputWidth;
double userInputHeight;
// initialise a scanner to be able to read the user input
Scanner reader = new Scanner(System.in);
// ask the user for input
System.out.print ("Enter the name of your box: ");
// read this input
name = (reader.nextLine());
// ask the user for input
System.out.print ("Enter the length of your box: ");
// read this input
userInputLength = (reader.nextDouble());
// ask the user for input
System.out.print ("Enter the width of your box: ");
// read this input
userInputWidth = (reader.nextDouble());
// ask the user for input
System.out.print ("Enter the height of your box: ");
// read this input
userInputHeight = (reader.nextDouble());
Block blockOne = new Block(name, userInputLength, userInputWidth, userInputHeight);
System.out.println( blockOne.showBoxAsString());
My object
package model;
import java.util.ArrayList;
import java.util.List;
public class Block {
// name variable of the figure
private String name;
// dimension variable of the figure
private double blockWidth;
private double blockHeight;
private double blockLength;
public Block() {
}
// form a block
public Block(String N, double L, double W, double H){
this.name = N;
this.blockLength = L;
this.blockWidth = W;
this.blockHeight = H;
}
// set the name
public void setBlockName(String N){ this.name = N; }
// set the name
public String getBlockName(){ return this.name; }
//set length method
public void setLength(double L)
{
this.blockLength = L;
}
//get length method
public double getLenght(){
return this.blockLength;
}
//set width method
public void setWidth(double W)
{
this.blockLength = W;
}
//get width method
public double getWidth(){
return this.blockWidth;
}
//set height method
public void setHeight(double H)
{
this.blockLength = H;
}
//get height method
public double getHeight(){
return this.blockHeight;
}
// method to calculate the surface of the shape (in this situation its a box)
public double calcSurfaceBox(){
// the formula to calculate the surface of the box is length times the width
double surface = 2 * (this.blockHeight * this.blockWidth) +
2 * (this.blockLength * this.blockHeight) +
2 * (this.blockWidth * this.blockLength) ;
// return the calculated value of surface
return surface;
}
// method to calculate the volume of the shape (in this situation it's a box)
public double calcVolumeBox(){
// the formula to calculate the volume is length times width times height
double volume = this.blockLength * this.blockWidth * this.blockHeight;
// return the calculated value of volume
return volume;
}
// a method to print a string to show the user the size of the shape (in this case a box.)
public String showBoxAsString(){
return String.format( "The box has a name: " + getBlockName() + "\n" +
"The box has a Length of: " + getLenght() + "\n" +
"The box has a Width of: " + getWidth() + "\n" +
"The height of the box is: " + getHeight());
}
}
i searched for multiple solutions but i can't figure it out. Is there anyone that could give me some tools or an idea?
my goal is to make my main code as clean as possible. so if anyone got an idea how i can simplify my main code that would be awesome.
Initialise an array of Block Objects
Block blocks[] = new Block[length];
To access each object use blocks[index]
Note: The array elements here store the reference variables to the object
Edit: index here means a block object perhaps blockOne

Getting an error when trying to run my last method

My program requires me to create 4 methods. 1 to take in length, 1 to take width, and 1 to calculate the area, and 1 to display the area. My code seems to be working up till the final method where i need to display my area. I've tried pretty much almost everything i can think of but it still isn't working.
import java.io.*;
import java.util.*;
public class Lab9Q2
{
public static double getLength()
{
Scanner keyboard = new Scanner (System.in); // Create Method
System.out.println ("Enter the length of the rectange"); // ask for the length
double length = keyboard.nextDouble();
return length;
}
public static double getWidth()
{
Scanner keyboard = new Scanner (System.in); // Create Method
System.out.println ("Enter the width of the rectange"); // ask for the width
double width = keyboard.nextDouble();
return width;
}
public static double getArea (double length, double width)
{
double area;
area = length*width;
return area;
}
public static double displayArea (double length, double width, double area)
{
System.out.println ("The length is: " + length);
System.out.println ("The width is: " + width);
System.out.println ("The area of the rectangle is: " + area);
}
public static void main (String [] args)
{
getLength();
getWidth();
displayArea(length, width, area);
}
}
The program should use all my method calls and then display the results properly but it wont do so.
You probably intended to use the three results from the helper methods in the final call to displayArea():
public static void main (String[] args) {
double length = getLength();
double width = getWidth();
double area = getArea(length, width);
displayArea(length, width, area);
}
Change the main block as below
public static void main(String [] args) {
double length = getLength();
double width = getWidth();
double area = getArea(length, width);
displayArea(length, width, area);
}
You missed the assignments and calling getArea function
Two ways you can get your code working
1) change your main method as
public static void main (String[] args) {
double length = getLength();
double width = getWidth();
double area = getArea(length, width);
displayArea(length, width, area);
}
2) Declare your length,width,area globally.
import java.io.*;
import java.util.*;
public class Lab9Q2
{
public static double length;
public static double width;
public static double area;
public static void getLength()
{
Scanner keyboard = new Scanner (System.in); // Create Method
System.out.println ("Enter the length of the rectange"); // ask for the length
length = keyboard.nextDouble();
}
public static void getWidth()
{
Scanner keyboard = new Scanner (System.in); // Create Method
System.out.println ("Enter the width of the rectange"); // ask for the width
width = keyboard.nextDouble();
}
public static void getArea (double length, double width)
{
area = length*width;
}
public static double displayArea (double length, double width, double area)
{
System.out.println ("The length is: " + length);
System.out.println ("The width is: " + width);
System.out.println ("The area of the rectangle is: " + area);
}
public static void main (String [] args)
{
getLength(); //Here length will get initialised
getWidth(); //Here width will get initialised
getArea(); //Here area will get calculated ..you also missed this statement
displayArea(length, width, area);
}
}

How to get JOptionPane to calculate area?

I have created this code, the GUI pops up and works perfectly, but the area is not being calculated correctly. Any Clue why? I am very new to Java coding, so any help is appreciated. Thanks in advance.
package pkg4.pkg2.pkgnew.project;
import javax.swing.JOptionPane;
public class NewProject {
public static void main(String[] args) {
String inputStr = JOptionPane.showInputDialog("Type 1 for the area of Triangle, 2 for area of Circle, 3 for Rectangle, and 0 for area of none of these.");
int i = Integer.parseInt(inputStr);
if (i == 1) {
String input = JOptionPane.showInputDialog("Enter the first value to calculate the area of a triangle: ");
int n1 = Integer.parseInt(inputStr);
String inp = JOptionPane.showInputDialog("Enter the second value to calculate the area of a triangle: ");
int n2 = Integer.parseInt(inputStr);
areaTriangle(n1, n2);
}
if (i == 2) {
String inpu = JOptionPane.showInputDialog("Enter a value to calculate the area of a circle: ");
double radius = Integer.parseInt(inputStr);
areaCircle(radius);
}
if (i == 3) {
String inp = JOptionPane.showInputDialog("Enter the first value to calculate the area of a rectangle: ");
int m1 = Integer.parseInt(inputStr);
String inp2 = JOptionPane.showInputDialog("Enter the second value to calculate the area of a rectangle: ");
int m2 = Integer.parseInt(inputStr);
areaRectangle(m1, m2);
} else {
return;
}
}
public static void areaTriangle(int n1, int n2) {
int areat = (n1 * n2) / 2;
JOptionPane.showMessageDialog(null, "The area of a triangle with your values is: " + areat);
}
public static void areaCircle(double radius) {
double areac = Math.PI * (radius * radius);
JOptionPane.showMessageDialog(null, "The area of a circle with your value is: " + areac);
}
public static void areaRectangle(int m1, int m2) {
int arear = (m1 * m2);
JOptionPane.showMessageDialog(null, "The area of a rectangle with your values is: " + arear);
}
public static void calcArea(int x) {
}
}
The problem with your code is that every time you parse the input into a string you are always using the same value of the string. Everytime you call your functions you are using all 1, 2, or 3 for your parameters into your area function calls. So you need to change the Integer.parseInt() to contain the new strings you get from the user like so:
String input = JOptionPane.showInputDialog("Enter the first value to calculate the area of a triangle: ");
int n1 = Integer.parseInt(input); //not inputStr <----------
String inp = JOptionPane.showInputDialog("Enter the second value to calculate the area of a triangle: ");
int n2 = Integer.parseInt(inp);//not inputStr <---------
areaTriangle(n1, n2);

How to Calculate BMI in Java

I'm writing a program that takes the users input for height and weight then calculates the Body Mass Index from this. It uses separate methods for height, weight and BMI, these methods are called from main. The problem I'm having is I have absolutely no clue how to put the input from weight and height methods into the BMI method. This is what the code looks like:
public class BMIProj {
static Scanner input = new Scanner(System.in);
public static int heightInInches()
{
System.out.println("Input feet: ");
int x;
x = input.nextInt();
System.out.println("Input Inches: ");
int y;
y = input.nextInt();
int height = x * 12 + y;
return height;
}
public static int weightInPounds()
{
System.out.println("Input stone: ");
int x;
x = input.nextInt();
System.out.println("Input pounds ");
int y;
y = input.nextInt();
int weight = x * 14 + y;
return weight;
}
public static void outputBMI()
{
}
public static void main(String[] args) {
heightInInches();
weightInPounds();
outputBMI();
}
Thanks in advance.
I advise you to do a little bit more learning in java, specifically variables, declaring, initializing, etc.. Also learn class, constructors, etc..
You need fields for the class to save the inputed variables
I created a constructor to initialize the variables
You don't need to return anything in the methods if all you are doing is assigning values to your class fields and outputting info.
I did the curtsy of calculating the bmi for you
Anyway
public class BMIProj {
static Scanner input = new Scanner(System.in);
// Class vars
int height;
int weight;
double bmi;
//Constructor
public BMIPrj(){
//Initialize vars
height = 0;
weight = 0;
bmi = 0;
}
public static void heightInInches()
{
System.out.println("Input feet: ");
int x;
x = input.nextInt();
System.out.println("Input Inches: ");
int y;
y = input.nextInt();
int height = x * 12 + y;
return height;
}
public static void weightInPounds()
{
System.out.println("Input stone: ");
int x;
x = input.nextInt();
System.out.println("Input pounds ");
int y;
y = input.nextInt();
int weight = x * 14 + y;
return weight;
}
public static void outputBMI()
{
System.out.println("BMI: " + (( weight / height ) x 703));
}
public static void main(String[] args) {
heightInInches();
weightInPounds();
outputBMI();
}
You can assign the output of a method to a parameter like so:
int weight = weightInPounds();
When calling a method, you can pass in parameters:
outputBMI(weight);
The rest is up to you.

Categories

Resources