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);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
import java.util.Scanner;
public class Geometry {
private Scanner scanner;
public double getCircleArea( double radius ) {
System.out.print("Enter circle area");
radius = scanner.nextDouble();
double RadiusSquared = Math.pow(radius, 2);
double circleArea = RadiusSquared * Math.PI;
return circleArea;
}
public double getRectangleArea( double length, double width ) {
System.out.print("Enter rectangle Length");
length = scanner.nextDouble();
System.out.print("Enter rectangle width");
width = scanner.nextDouble();
double rectangleArea = length * width;
return rectangleArea;
}
public double getTriangleArea( double base, double height ) {
System.out.println("enter triangle base");
base = scanner.nextDouble();
System.out.println("enter triangle height");
height = scanner.nextDouble();
double triangleArea = (base* height)/2;
return triangleArea;
}
public static void main( String[] args ) {
new Geometry().go();
}
private void go() {
scanner = new Scanner(System.in);
// main processing logic including input and output goes here.
int userNum = 0;
int secNum = 0;
while (userNum <= 0) {
System.out.println("1. Area of circle\n" + "2. Area of rectangle\n" + "3. Area of triangle\n" + "9. Exit");
userNum = scanner.nextInt();
if (userNum == 1){
System.out.println(getCircleArea(userNum));
}
else if (userNum == 2){
System.out.println(getRectangleArea(userNum,secNum));
}
else if (userNum == 3){
System.out.println(getTriangleArea(userNum,secNum));
}
else if (userNum == 9){
}
}
}
}
So I wanted it to only be able to put these 4 numbers but I am not sure if this is better than just a while loop, which I think I know how to do. Also what do you think about the actual geometry?
You can try the below code and figure out what's problematic in your code.
import java.util.Scanner;
public class Geometry {
private Scanner scanner;
public double getCircleArea( double radius ) {
System.out.print("Enter radius of circle to find area: ");
radius = scanner.nextDouble();
double RadiusSquared = Math.pow(radius, 2);
return RadiusSquared * Math.PI;
}
public double getRectangleArea( double length, double width ) {
System.out.print("Enter rectangle Length: ");
length = scanner.nextDouble();
System.out.print("Enter rectangle width: ");
width = scanner.nextDouble();
return length * width;
}
public double getTriangleArea( double base, double height ) {
System.out.print("enter triangle base: ");
base = scanner.nextDouble();
System.out.print("enter triangle height: ");
height = scanner.nextDouble();
return (base*height)/2;
}
public static void main( String[] args ) {
new Geometry().go();
}
private void go() {
scanner = new Scanner(System.in);
// main processing logic including input and output goes here.
int userNum = 0;
int secNum = 0;
while (userNum <= 0) {
System.out.println("1. Area of circle\n" + "2. Area of rectangle\n" + "3. Area of triangle\n");
System.out.print("choose a number: ");
userNum = scanner.nextInt();
if (userNum == 1) { System.out.println("Area of circle is " + getCircleArea(userNum)); }
else if (userNum == 2){ System.out.println("Area of rectangle is " + getRectangleArea(userNum,secNum)); }
else if (userNum == 3){ System.out.println("Area of triangle is " + getTriangleArea(userNum,secNum)); }
else System.exit(0);
}
}
}
It's depending on what your needs.
If you want to always display the menu selection bar once after user got the area, while is a must.
If not, just use Map to map each user's selection as to avoid bunches of if else block
//THIS IS FOR OPTION2
//no need the parameter, radius is depending input in the method scope
public double getCircleArea() {//...}
//...
public static void main( String[] args ) {
Map<Integer, Func> map = new HashMap();
map.put(num1, () -> getCircleArea());
//map.put(num2, xxx()) etc
new Geometry().go();
}
private void go() {
//...
map.get(userNum)
}
interface Func{
void execute();
}
(ps, from the code, seen scanner.nextDouble(), scanner.nextInt() to get from input of scanner. I think it is an alert when using different API to maintain the same functionality.
Because it violates encapsulation principle. java.util.Scanner already has the javadoc to interpret these, thus you should check from your side.
)
Hi I was wondering if someone could help me make it so when I choose an option in my code when the program runs, it skips all the other options that weren't chosen and only uses the code inputted by the user. So only the specific parts in the code should be printed but I don't know how to skip over code. There is probably things I should remove and then things I should add but I need help.
package test;
import java.util.Scanner;
import java.text.NumberFormat;
public class Test
{
static Scanner input = new Scanner( System.in );
public static void main(String[] args)
{
//Variables
String Option;
int a;
int Base;
int Height;
int Length;
int Width;
int Radius;
int r;
int b;
double Area;
//Menu
System.out.println("Welcome to the Area Calculator");
System.out.println("");
System.out.println("1. Square");
System.out.println("2. Rectangle");
System.out.println("3. Circle");
System.out.println("4. Triangle");
System.out.println("5. Quit");
System.out.println("Please enter the number of the shape you would like to calculate the area for.");
Option=input.next();
}
public static void Sqaure(String[] args)
{
System.out.println("Please enter the length of one side.");
int a=input.nextInt();
System.out.println("Please enter the length of one side.");
double area = a*a;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Rectangle(String[] args)
{
System.out.println("Please enter the length.");
int Length=input.nextInt();
System.out.println("Please enter the width.");
int Width=input.nextInt();
double area = Length*Width;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Circle(String[] args)
{
System.out.println("Please enter the radius.");
int r=input.nextInt();
double Radius = r*r;
double area = Math.PI * Radius;
System.out.println("The area of the given shape is " + area + " square units.");
}
{
System.out.println("Please enter the base length.");
int b=input.nextInt();
double Base = b * .5;
System.out.println("Please enter the height lenth.");
int Height=input.nextInt();
double area = Base * Height;
System.out.println("The area of the given shape is " + area + " square units.");
}
}
So, it is clear to me you're very new with Java and you're learning! So I went ahead and made a complete working version of what you are trying to do.
Although it is a simple program Ill go through what each section does.
Prompt Method
Asks the user which area they want to find, this method has the direct answer to your question in the form of a series of if/if else statements. It gets the input from the user and then goes through the series of if/if else statements, seeing if the value entered matches any of them, if it does then it runs that section of code and skips the rest. If a number other then 1-4 is entered, it quits the program (see the else statement), see this page for more info on if statements. I opted for a bunch of if statements but there is a better, cleaner way, but it is a little confusing if you are brand new, see here to learn about those.
Area Methods
These are all pretty much the same except for he way they calculate the areas. They first prompt the user for the required measurements for that shape and assign those entered values to variables, then it prints out the resulting area after running the values through a calculation, then the program stops.
Main Method
All the main method is doing is calling prompt, that keeps it clean, you don't really ever want to do anything but call other methods or create objects in the main method, so most people put the nitty gritty somewhere else and call it.
Below is the working code
Go ahead and paste into a doc and run it, just be aware that I did not bother to add any error catching to keep it simple so keep it to whole numbers without decimals (also called ints, eg. 1, 2, 4, not 4.3, 5.4, etc.)
Side note:
In your methods you have (String args[]) in the brackets, this is not needed, in fact it will cause trouble, that is only used in the main method and is a relatively advanced way of providing input to the program, for now you can keep to leaving the brackets empty.
import java.util.*;
public class Area
{
public static void main(String args[])
{
prompt(); //Calls prompt method
}
//Prompt Method
public static void prompt()
{
int option;
Scanner input = new Scanner(System.in);
//Ask the user which shape they want to find the area of
System.out.println("Select from the following shapes to calulate the area:");
System.out.println("Rectangle -- 1\nCircle -- 2\nTriangle -- 3\nQuit -- 4\n");
System.out.print("Your option: ");
option = input.nextInt();
System.out.println();
//THIS IS THE PART THAT DIRECTLY PERTAINS TO YOUR QUESTION
if(option == 1)
{
rectangle();
}
else if(option == 2)
{
circle();
}
else if(option == 3)
{
triangle();
}
else
{
System.out.println("Program stopped by user"); //For stopping the program when they want to quit instead
System.exit(0);
}
}
//Rectangle Method
public static void rectangle()
{
double h;
double b;
Scanner input = new Scanner(System.in);
System.out.println("RECTANGLE");
System.out.print("Enter Height: ");
h = input.nextDouble();
System.out.print("Enter Base: ");
b = input.nextDouble();
System.out.print("\nArea of Rectangle = " + (h*b) + "\n");
}
//Circle Method
public static void circle()
{
double pi = 3.14;
double radius;
Scanner input = new Scanner(System.in);
System.out.println("CIRCLE");
System.out.print("Enter radius: ");
radius = input.nextDouble();
System.out.print("\nArea of Circle = " + (pi*(radius*radius)) + "\n");
}
//Triangle Method
public static void triangle()
{
double h;
double b;
Scanner input = new Scanner(System.in);
System.out.println("TRIANGLE");
System.out.print("Enter Height: ");
h = input.nextDouble();
System.out.print("Enter Base: ");
b = input.nextDouble();
System.out.print("\nArea of Triangle = " + ((h*b)/2) + "\n");
}
}
package test;
import java.util.Scanner;
import java.text.NumberFormat;
public class Test
{
static Scanner input = new Scanner( System.in );
public static void main(String[] args)
{
//Variables
String Option;
int a;
int Base;
int Height;
int Length;
int Width;
int Radius;
int r;
int b;
double Area;
String [] inputString = new String [50];
//Menu
System.out.println("Welcome to the Area Calculator");
System.out.println("");
System.out.println("1. Square");
System.out.println("2. Rectangle");
System.out.println("3. Circle");
System.out.println("4. Triangle");
System.out.println("5. Quit");
System.out.println("Please enter the number of the shape you would like to calculate the area for.");
Option=input.next();
switch (Option) {
case "1": Sqaure(inputString);
break;
case "2": Rectangle(inputString);
break;
case "3": Circle(inputString);
break;
default: someExtraFig(inputString);
break;
}
}
public static void Sqaure(String[] args)
{
System.out.println("Please enter the length of one side.");
int a=input.nextInt();
System.out.println("Please enter the length of one side.");
double area = a*a;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Rectangle(String[] args)
{
System.out.println("Please enter the length.");
int Length=input.nextInt();
System.out.println("Please enter the width.");
int Width=input.nextInt();
double area = Length*Width;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void Circle(String[] args)
{
System.out.println("Please enter the radius.");
int r=input.nextInt();
double Radius = r*r;
double area = Math.PI * Radius;
System.out.println("The area of the given shape is " + area + " square units.");
}
public static void someExtraFig(String ...s)
{
System.out.println("Please enter the base length.");
int b=input.nextInt();
double Base = b * .5;
System.out.println("Please enter the height lenth.");
int Height=input.nextInt();
double area = Base * Height;
System.out.println("The area of the given shape is " + area + " square units.");
}
}
I have received four error messages in my code. It states that in modes 2 and 4, dArea cannot be resolved to a variable. Later in the code, the same variable is said to be duplicated even though it has only been assigned value, used, and returned. How can I fix these issues?
import javax.swing.JOptionPane;
public class Lab7
{
public static void main(String args [])
{
// Created by Makayla Scull, period 4B
String sMode;
int iMode = 0;
sMode = JOptionPane.showInputDialog("Menu: \n [Square: Press 1] \n [Rectangle: Press 2] \n [Circle: Press 3] \n [Triangle: Press 4] \n [Trapezoid: Press 5] \n [To Exit: Press 6]");
iMode = Integer.parseInt(sMode);
while(iMode == 0);
{
if (iMode == 1)
{
Geometry.methodSquare();
}
if (iMode == 2)
{
Geometry.methodRectangle(dArea);
}
if (iMode == 3)
{
Geometry.methodCircle();
}
if (iMode == 4)
{
Geometry.methodTriangle(dArea);
}
if (iMode == 5)
{
Geometry.methodTrapezoid();
}
if (iMode == 6)
{
break;
}
}
}
}
class Geometry
{
public static void methodSquare()
{
String sLength;
double dLength;
double dArea;
int exp = 2;
JOptionPane.showMessageDialog(null, "You chose the square.");
sLength = JOptionPane.showInputDialog("Enter the side length of the square.");
dLength = Double.parseDouble(sLength);
dArea = Math.pow(dLength, exp);
JOptionPane.showMessageDialog(null, "The area of the square is " + dArea);
}
public static double methodRectangle(double dArea)
{
String sLength;
String sWidth;
double dLength;
double dWidth;
JOptionPane.showMessageDialog(null, "You chose the rectangle.");
sLength = JOptionPane.showInputDialog("Enter the length of the rectangle.");
sWidth = JOptionPane.showInputDialog("Enter the width of the rectangle.");
dLength = Double.parseDouble(sLength);
dWidth = Double.parseDouble(sWidth);
double dArea = (dLength * dWidth);
JOptionPane.showMessageDialog(null, "The area of the rectangle is " + dArea);
return dArea;
}
public static double methodCircle()
{
String sRadius;
double dRadius;
int exp = 2;
JOptionPane.showMessageDialog(null, "You chose the circle.");
sRadius = JOptionPane.showInputDialog("Enter the radius of the circle.");
dRadius = Double.parseDouble(sRadius);
double dArea = Math.pow(dRadius, exp) * Math.PI;
JOptionPane.showMessageDialog(null, "The area of the circle is " + dArea);
return dArea;
}
public static double methodTriangle(double dArea)
{
String sBase;
String sHeight;
double dBase;
double dHeight;
JOptionPane.showMessageDialog(null, "You chose the triangle.");
sBase = JOptionPane.showInputDialog("Enter the base length of the triangle.");
dBase = Double.parseDouble(sBase);
sHeight = JOptionPane.showInputDialog("Enter the height of the triangle.");
dHeight = Double.parseDouble(sHeight);
double dArea = (dBase * dHeight) / 2;
JOptionPane.showMessageDialog(null, "The area of the triangle is " + dArea);
return dArea;
}
public static void methodTrapezoid()
{
String sHeight;
String sBase1;
String sBase2;
double dHeight;
double dBase1;
double dBase2;
JOptionPane.showMessageDialog(null, "You chose the trapezoid.");
sHeight = JOptionPane.showInputDialog("Enter the height of the trapezoid.");
dHeight = Double.parseDouble(sHeight);
sBase1 = JOptionPane.showInputDialog("Enter the length of the first base of the trapezoid.");
dBase1 = Double.parseDouble(sBase1);
sBase2 = JOptionPane.showInputDialog("Enter the length of the second base of the trapezoid.");
dBase2 = Double.parseDouble(sBase2);
double dArea = ((dBase1 + dBase2) * dHeight) / 2;
JOptionPane.showMessageDialog(null, "The area of the trapezoid is " + dArea);
}
}
in modes 2 and 4, dArea cannot be resolved to a variable
That's because you never defined that variable. You try to use it:
Geometry.methodRectangle(dArea);
But nowhere in that scope have you defined it. A value has to exist before it can be used.
the same variable is said to be duplicated
Your methods define a variable as a parameter to the method:
public static double methodRectangle(double dArea)
But then also try to declare it again within the method:
double dArea = (dLength * dWidth);
Just as the error is telling you, a variable can only be declared once in any given scope. If you try to have two variables by the same name in the same scope then the compiler would have no way of knowing which one you're referring to.
I've started a few demos which all have worked fine. I've recently stepped up the complexity and put together a paint program working out the area in metric and imperial. Although I don't get any compilation errors, When I try and run the program in Eclipse it misses out the calculation part. Hope somebody can help:
//program begin
package paintCalculation;
import java.util.Scanner;
public class PaintCoverageV1
{
public static void main(String[] args)
{
//Variables
double roomArea = 0, roomHeightSq = 0, roomWidthSq = 0, coverage = 172.22, wastage = 1.10;
double roomHeightRec, roomWidthRec, roomLengthRec;
double totalpaintgallons = (roomArea / coverage) * wastage;
double totalpaintlitres = totalpaintgallons * (4.54);
double metresconversion = 10.7;
char areaKnown, Y = 0, N = 0;
char con, I = 0, M = 0;
char roomType, S = 0, R = 0;
//Heading
System.out.println("Paint Coverage Calculator");
Scanner keyboard = new Scanner(System.in);
//areaKnown
System.out.println("Do you know wall area? (Y for YES, N for NO) ");
areaKnown = keyboard.next().charAt(0);
if (areaKnown == Y)
{
System.out.println("Enter room area ");
roomArea = keyboard.nextDouble();
}
else if (areaKnown == N)
{
//roomType
System.out.println("Enter room shape (S for Square, R for Rectangle) ");
roomType = keyboard.next().charAt(0);
if (roomType == S)
{
System.out.println("Enter wall height ");
roomHeightSq = keyboard.nextDouble();
System.out.println("Enter wall width ");
roomWidthSq = keyboard.nextDouble();
roomArea = (roomHeightSq * roomWidthSq) * 4;
}
else if (roomType == R)
{
System.out.println("Enter wall height ");
roomHeightRec = keyboard.nextDouble();
System.out.println("Enter wall length ");
roomLengthRec = keyboard.nextDouble();
System.out.println("Enter wall width ");
roomWidthRec = keyboard.nextDouble();
roomArea = ((roomHeightRec * roomWidthRec) + (roomLengthRec * roomHeightRec)) * 2;
}
}
{
//metricConversion
System.out.println("Which conversion is required? (M = Metric, I = Imperial)");
con = keyboard.next().charAt(0);
keyboard.close();
if (con == I)
{
System.out.print("Total amount of paint in gallon(s) required is " + totalpaintgallons);
System.out.print("Total amount of paint in litre(s) required is " + totalpaintlitres);
}
else if (con == M)
{
coverage = coverage / metresconversion;
System.out.print("Total amount of paint in gallon(s) required is " + totalpaintgallons);
System.out.print("Total amount of paint in litre(s) required is " + totalpaintlitres);
}
}
}
}
//program end
You need to change
if (areaKnown == Y)
to
if (areaKnown == 'Y')
and so on.
You current code compares areaKnown to the value of variable Y, which is zero, instead of comparing it to the character 'Y'.
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);
}