Getting an error when trying to run my last method - java

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

Related

I don't understand where does $64 comes from

Assume that a gallon of paint cover's about 350 square feet of wall space, ask a user to enter length, width and height. The methods should do the following:
Calculate the wall area for a room
Passes the calculated wall area to another method that calculates and returns the number of gallons of paint needed
Display the number of gallons needed
Computes the price based on a paint price $32 per gallon, assuming that the painter can buy any fraction of a gallon of paint at the same price as a whole gallon.
returns the price to the main method.
The main() method displays the final price. Example: the cost to paint a 15-by-20 room with 10-foot ceilings is $64.
Here us what I did, and I'm failing to get that $64
public static void main(String[] args){
double l,h,w;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the height: ");
h=sc.nextDouble();
System.out.print("Enter the width: ");
w=sc.nextDouble();
System.out.print("Enter the length: ");
l=sc.nextDouble();
disGallons(calArea(h, w, l));
disPrice(price(calGallon(calArea(h, w, l))));
}
public static double calArea(double h,double w, double l){
double area=2*((w*h)+(l*w)+(l*h));
return area;
}
public static double calGallon(double area){
double gallons= area/350;
return gallons;
}
public static void disGallons(double gallons){
System.out.println("Gallons needed: "+gallons);
}
public static double price(double gallon){
final double gallPrice=32;
return (int)(gallPrice*gallon);
}
public static void disPrice(double price){
System.out.println("Total Price is: $"+price);
}
Here's how I'd do it.
package io.duffymo;
/**
* Size the amount of paint needed
* #link ...
*/
public class PaintSizing {
public static final double PRICE_PER_GALLON_USD = 32.0;
public static final double SQ_FEET_PER_GALLON = 350.0;
public static double area(double h, double w, double l) {
return 2.0*(w + l)*h;
}
public static double gallons(double area) {
return area / SQ_FEET_PER_GALLON;
}
public static double price(double gallons) {
return gallons * PRICE_PER_GALLON_USD;
}
}
It's never too soon to learn about JUnit:
package io.duffymo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class PaintSizingTest {
#Test
public void testSizing() {
// setup
double l = 15.0;
double w = 20.0;
double h = 10.0;
double expectedArea = 700.0;
double expectedGallons = 2.0;
double expectedPrice = 64.0;
// exercise
double actualArea = PaintSizing.area(h, w, l);
double actualGallons = PaintSizing.gallons(actualArea);
double actualPrice = PaintSizing.price(actualGallons);
// assert
Assertions.assertEquals(expectedArea, actualArea, 0.001);
Assertions.assertEquals(expectedGallons, actualGallons, 0.001);
Assertions.assertEquals(expectedPrice, actualPrice, 0.001);
}
}

myRectangle.calculateArea(); returns error "package myRectangle does not exist"

Rectangle
public class Rectangle {
private double width;
private double length;
public Rectangle(double L, double W){
length = L;
width = W;
}
public void setLength(double Length){
if (length>=0 && length <=20)
length = Length;
else{
length = 0;
}
}
public double getLength(){
return length;
}
public void setWidth(double Width){
if (width>=0 && length <=20)
width = Width;
else{
width = 0;
}
}
public double getWidth(){
return width;
}
public void calculatePerimeter(){
System.out.println("The perimeter of rectangle is: " + 2 * (length + width));
}
public void calculateArea(){
System.out.println("The area of the rectangle is: " + (length * width));
}
}
TestRectangle
import java.util.Scanner;
public class TestRectangle {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Rectangle myRectangle = new Rectangle (0,0);//I did the same thing in a
//previous assignment, and someone else who did this assignment (code found
//online) also did this. It worked before but seems useless now?
System.out.println("Enter length: ");
double L = input.nextDouble();
System.out.println();
System.out.println("Enter width: ");
double W = input.nextDouble();
System.out.println();
}
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
//<identifier> expected, package myRectangle does not exist
}
I am trying to create a program "Rectangle" to calculate the area and perimeter of a rectangle, and then create a test program to run program "Rectangle"
I have copied code from a previous assignment called "Date", where the basic idea is similar, but when I get to the end of the program where I need to call on "calculateArea();" and "calculatePerimeter();" in the test program, I get an error telling me that package myRectangle doesn't exist.... can someone tell me why this is happening? A similar code worked in the previous assignment, and I found someone else's code for the same "Rectangle" program and it shows the same error. Did I do something wrong or is there something wrong with my NetBeans?
This is the code I based the Rectangle and TestRectangle program off of
Date
public class Date {
private int month;
private int day;
private int year;
public Date(int m, int d, int y){
month = m;
day = d;
year = y;
}
public void setMonth(int Months){
if(Months>=0 && Months <= 12)
month=Months;
else{
month=0;
}
}
public int getMonth(){
return month;
}
public void setDay(int Days){
if(Days>= 0 && Days<=31)
day = Days;
else{
day=0;
}
}
public int getDay(){
return day;
}
public void setYear(int Years){
year=Years;
}
public int getYear(){
return year;
}
public void displayDate(){
System.out.printf
("%d/%d/%d\n", getMonth(), getDay(), getYear() );
}
}
TestDate
import java.util.Scanner;
public class DateTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Date myDate = new Date(0,0,0);
System.out.println("Justine Dodge, assignment 6\n");
System.out.println("Please enter month: ");
int m = input.nextInt();
myDate.setMonth(m);
System.out.println();
System.out.println("Enter day: ");
int d = input.nextInt();
myDate.setDay(d);//assign d to Day?
System.out.println();//output blank line
System.out.println("Enter year: ");
int y = input.nextInt();
myDate.setYear(y);
System.out.println();
myDate.displayDate();
}
}
in the TestRectangle you are closing the main method before calling these functions
} // this should be at at the end of the main function
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
i.e
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
}
This will remove the compilation error. Now when you run it , you will get both area and perimeter as 0 because in the constructor , you are passing values of length and width as 0 and not really using the length and width taken as input.
To resolve this issue, insstead of passing 0,0 in constructor,
try to pass L,W in constructor like this
Rectangle myRectangle = new Rectangle (L,W);
myRectangle.getLength()); //
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();
import java.util.Scanner;
public class TestRectangle {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
// Rectangle myRectangle = new Rectangle (0,0);//I did the same thing in a
//previous assignment, and someone else who did this assignment (code found
//online) also did this. It worked before but seems useless now?
System.out.println("Enter length: ");
double L = input.nextDouble();
System.out.println();
System.out.println("Enter width: ");
double W = input.nextDouble();
System.out.println();
Rectangle myRectangle = new Rectangle (L,W);
// System.out.println("get length " + myRectangle.getLength());
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
//<identifier> expected, package myRectangle does not exist
}
}
then you will get o/p like this

How to receive user-input and pass it to object?

I have a java program which will receive user-input and pass it an object to find the area of a circle.
import java.util.Scanner;
public class Area{
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
double n = reader.nextDouble();
reader.close();
Circle c = new Circle();
c.radius = n;
c.area=3.148*c.radius*c.radius;
System.out.println(c.radius);
}
}
class Circle {
double radius;
double area;
}
The program receives user input but it's not performing the operation.
How to make this work
Regards
The operation performs well, but you just don't pass the correct argument to System.out.println. At the end you pass c.radius instead of c.area and the result of operation isn't written to the console. This is what you should write at the end od main method:
System.out.println(c.area)
System.out.println(c.area);
That should fix your problem.
Although, if I can suggest, you're better of doing these calculations in your Circle class. It's good coding practice.
public class Main {
public static void main(String[] args) {
System.out.println("Enter a number: ");
Scanner reader = new Scanner(System.in);
double n = reader.nextDouble();
reader.close();
Circle circle = new Circle(n);
double area = circle.getArea();
System.out.printf("The area is %f", area);
}
}
class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return 3.14 * radius * radius;
}
public double getRadius() {
return radius;
}
}
Please look at this sample implementation:
class Circle {
private static final double PI = 3.148;
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double calculateArea() {
return PI * radius * radius;
}
public double getRadius() {
return radius;
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Enter a number: ");
Scanner reader = new Scanner(System.in);
double input = reader.nextDouble();
reader.close();
Circle circle = new Circle(input);
double area = circle.calculateArea();
System.out.printf("My radius is %f%n", circle.getRadius());
System.out.printf("My area is %f", area);
}
}
Your initial mistake is that you were printing c.radius instead of c.area.
The constructor public Circle(double radius) makes sure that a Circle object always has a radius whenever one is created. A circle without a radius doesn't really make sense.
Circle should be responsible for everything related to a circle. That's why the calculation of the area, a typical circle-related math operation, should be handled by Circle and not outside in main().

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.

Calculating perimeter and area of a rectangle

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

Categories

Resources