Beginner Java: Variable Scope Issue - java

I'm practicing some work from my java book and I'm having an issue with getting a method to use a variable for a calculation. Please note that this is a work in progress and I'm only trying to get it to use the circleArea method to calculate the area of a circle at the moment. Here is the necessary code:
public class Geometry
{
public static void printMenu()
{
System.out.println("This is a geometry calculator\nChoose what you would like to calculate" + "\n1. Find the area of a circle\n2. Find the area of a rectangle\n3."
+ " Find the area of a triangle\n4. Find the circumference of a circle."
+ "\n5. Find the perimeter of a rectangle\n6. Find the perimeter of a triangle"
+ "\nEnter the number of your choice:");
}
public static void circleArea(double area)
{
System.out.println(Math.PI*Math.pow(radius, 2));
}
public static void main(String[] args)
{
int choice; //the user's choice
double value = 0; //the value returned from the method
char letter; //the Y or N from the user's decision to exit
double radius; //the radius of the circle
double length; //the length of the rectangle
double width; //the width of the rectangle
double height; //the height of the triangle
double base; //the base of the triangle
double side1; //the first side of the triangle
double side2; //the second side of the triangle
double side3; //the third side of the triangle
}
}

Please declare a variable of class and call the function from it.
public class Geometry
{
int choice; //the user's choice
double value = 0; //the value returned from the method
char letter; //the Y or N from the user's decision to exit
double radius; //the radius of the circle
double length; //the length of the rectangle
double width; //the width of the rectangle
double height; //the height of the triangle
double base; //the base of the triangle
double side1; //the first side of the triangle
double side2; //the second side of the triangle
double side3; //the third side of the triangle
public static void printMenu()
{
System.out.println("This is a geometry calculator\nChoose what you would like to calculate"
+ "\n1. Find the area of a circle\n2. Find the area of a rectangle\n3."
+ " Find the area of a triangle\n4. Find the circumference of a circle."
+ "\n5. Find the perimeter of a rectangle\n6. Find the perimeter of a triangle"
+ "\nEnter the number of your choice:");
}
public static void circleArea(double area)
{
System.out.println(Math.PI*Math.pow(radius, 2));
}
public static void main(String[] args)
{
Geometry g = new Geometry();
g.printMenu();
}
}

Related

why class Circle is not working in Java or I made any mistake, Please answer

I am trying to calculate the area of the circle using class and object in Java, but the output is not as I want. I want an answer as 78.5 but the area = 0.0, why? Here is the code below-
package com.company;
import java.util.Scanner;
class Circle{
double r;
double area= Math.PI*r*r;
}
public class practice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Circle c = new Circle();
System.out.print("Enter the radius of circle: ");
c.r = sc.nextDouble();
System.out.println("The area of circle is: "+ c.area);
}
}
The result I got is-
Enter the radius of circle: 5
The area of circle is: 0.0
Process finished with exit code 0
Try this code, should work. Compare with what you have done so far: You are calculating area before the user has entered data. I suggest you to read about constructors
package com.company;
import java.util.Scanner;
class Circle{
double r = 0.0;
double area= 0.0;
public Circle( double r ){
this.r = r;
this.area = Math.PI*this.r*this.r;
}
}
public class practice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the radius of circle: ");
Circle c = new Circle( sc.nextDouble() );
System.out.println("The area of circle is: "+ c.area);
}
}
At new Circle(), r is initialized to be 0 (since no explicit assignment is given) and area is calculated with this and thus store the value 0.
At c.r = sc.nextDouble();, c.r is reassigned to hold the scanned value. However, area will not be automatically recomputed based on this assignment and hence remains at 0.
You have to understand that the code at the constructor will be run only once when an object is created.
If you have no constructor (like in your example code above) then the code will be run when the program is run. The values of not initialized double values will be 0.0. That's the problem in your case too. Your area calculation will be translated to area = 3.14 * 0.0 * 0.0. I would suggest following the conventions and best practices this way:
class Circle
{
private double radius = 0.0; // Best practice is to declare the variable private and access it through getters & setters
public Circle(double radius)
{
this.radius = radius;
}
public double calculateArea()
{
return Math.PI * this.radius * this.radius ;
}
public double getRadius()
{
return radius;
}
public void setRadius(double radius)
{
this.radius = radius;
}
}
public class Practice
{
public static void main(String[] args)
{
Circle c = new Circle(5);
System.out.println("Area of this circle is : " + c.calculateArea());
}
}

Getting .set to work with an object array in Java

So I'm trying to make a program where you put in a radius and it spits out the area, diameter etc. but whenever I run the app it crashes. Here's what I've got if anyone can help that would be much appreciated
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MeasureC[] mc = new MeasureC[5];
int i=0;
int p =5;
for(i=0;i<=p;i++)
{
System.out.println("What do you want the radius to be?");
double UserRad = scan.nextDouble();
mc[i].setRadius(UserRad);
mc[i].setArea();
mc[i].setDiameter();
mc[i].setCircumfrence();
System.out.println(mc[i].getRadius());
System.out.println(mc[i].getArea());
System.out.println(mc[i].getDiameter());
System.out.println(mc[i].getCircumfrence());
}
Here's the second class:
public class MeasureC {
private double radius, area, diameter, circumfrence;
public double getRadius() {
return radius;
}
public void setRadius(double newRadius) {
radius = newRadius;
}
public double getArea() {
return area;
}
public void setArea() {
area = 3.14*radius;
}
public double getDiameter() {
return diameter;
}
public void setDiameter() {
diameter = 2*radius;
}
public double getCircumfrence() {
return circumfrence;
}
public void setCircumfrence() {
circumfrence = 3.14*(2*radius);
}
MeasureC[] mc = new MeasureC[5];
This doesn't create an array of 5 MeasureC objects, it just allocates the space for them in memory. So, currently, every index points to null. That means that in your for loop when you try and access a particular element in your array you will get an error as .setRadius() etc... is not a method of null:
mc[i].setRadius(UserRad); // mc[i] is null
So, to fix this issue, you can create a new instance of your MeasureC class at each iteration and set it at your index:
for(i = 0; i < p; i++) { // set to i < p as max index in your array is 4 (not 5)
mc[i] = new MeasureC();
// code...
}
Replace:
for(i=0;i<=p;i++)
by:
for(i=0;i<p;i++)
as now you iterate 6 times on 5 dimension array and got ArrayIndexOutOfBoundsException
I assume you get a NullPointerException at the line mc[i].setRadius(UserRad);.
Think about what that means. Then it should be obvious what line you have to add before that to fix the problem.
Hint: Think about how Java does array initializations.
Assuming you want the radius to be the only input data allowed, we can try refactoring your code as (see notes below):
public class MeasureC {
private double radius, area, diameter, circumference;
public MeasureC (double radius) {
diameter = 2.0d * radius;
circumference = Math.pi * diameter;
area = Math.pi * Math.pow(radius, 2);
}
public double getRadius(){
return radius;
}
public double getArea(){
return area;
}
public double getDiameter(){
return diameter;
}
public double getCircumfrence(){
return circumfrence;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int p = 5;
MeasureC[] mc = new MeasureC[p];
for (int i=0; i <= p; i++) {
System.out.println("What do you want the radius to be?");
double userRad = scan.nextDouble();
mc[i] = new Measure(userRad);
System.out.println(mc[i].getRadius());
System.out.println(mc[i].getArea());
System.out.println(mc[i].getDiameter());
System.out.println(mc[i].getCircumfrence());
}
}
Notes:
I expose a single constructor in your MeasureC class which accepts an input radius as a double. Inside that constructor I compute, using that input radius, the diameter, circumference, and area.
Since you only want the circle to be configurable via the radius, I removed setters for the diameter, circumference, and area.
A problem you had in your main() method was that you were not instantiating your MeasureC instances with new. I am doing this now.
Java naming conventions say that variable names should begin with lowercase letters, while class names begin with uppercase. Both are camelcase for subsequent letters. You should stick with this convention.

Multiple Methods in determining Area of Rectangle

The question that I am really stuck on is this:
Write a program that asks the user to enter the width and length of a rectangle, and then display the rectangle’s area. The program should call the following methods:
• getLength – This method should ask the user to enter the rectangle’s length, and then return that value as a double.
• getWidth – This method should ask the user to enter the rectangle’s width, and then return that value as a double.
• getArea – This method should accept the rectangle’s length and width as arguments, and return the rectangle’s area. The area is calculated by multiplying the length by width.
• displayArea – This method should accept the rectangle’s length, width, and area as arguments, and display them in an appropriate message to the screen.
I don't know how to complete this code because right now what I have is this:
import java.util.Scanner;
public class WidthLengthAreaMethods
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
double length;
double width;
double area;
length = getLength();
width = getWidth();
area = getArea(double length, double width);
displayData(length, width, area);
}
public static double getLength()
{
System.out.println("Enter length. ");
length = keyboard.nextDouble();
System.out.println("The length is " + length);
}
public static double getWidth()
{
double width;
System.out.println("Enter width. ");
width = keyboard.nextDouble();
System.out.println("The width is " + width);
}
public static double getArea()
{
double length;
double width;
double area = length * width;
System.out.println("The area is: " + area);
}
public static void displayData(double length, double width, double area)
{
System.out.println(" The length is: \t" + length);
System.out.println(" The width is: \t" + width);
System.out.println(" The area is: \t" + area);
}
}
What am I screwing up on and how would I go about fixing it? I am a beginner in programming so please bear with me :D.
Thanks guys!!
Since your program is broken up into several methods, the data inside each method is local unless you store it inside the class itself.
For example, your helper functions for getLength() and getWidth() wouldn't be able to access your keyboard Scanner unless you declared it outside of the main method, as such:
import java.util.Scanner;
public class WidthLengthAreaMethods {
Scanner keyboard = new Scanner( System.in );
// Initialized within the class, but outside of any methods
public static void main( String[] args ) {
double length = getLength();
double width = getWidth();
double area = getArea( length, width );
displayData( length, width, area );
}
}
Another alternative would be to pass your Scanner to each of the helper methods in their function calls, e.g.
public static double getLength( Scanner keyboard ){}
While passing the Scanner to each function separately would allow your methods to work as intended, the first option is slightly more readable.
The other thing to consider is that when a method has a return value, such as a double in the case of getLength(), getWidth(), and getArea(), the piece of code calling the function is expecting some variable of that type to be returned. In the case of a void function, such as main() or displayData(), the method states that it will not return a variable of any specific type.
Therefore, when you set length to equal getLength(), what you're trying to do is set the value of your local length variable to equal the value coming back from your helper function. If that value will never be sent, the program will most likely be unable to compile - an error will be thrown stating something along the lines of "expected type double" when you try to call that function. To fix the compiler error, a return statement needs to be added in to the helper functions, such as:
Scanner keyboard = new Scanner( System.in );
public static double getWidth() {
System.out.println("Enter width.");
double width = keyboard.nextDouble(); // Sets the value to return to your main function
System.out.println("The width is " + width);
return width; // Returns the value to your main function
// Causes any code underneath the return statement to be ignored
}
Combining all of that should allow the compiler errors to stop, and make your program work correctly.
Here is the working solution
import java.util.Scanner;
public class WidthLengthAreaMethods {
public static void main(String[]args)
{
double length;
double width;
double area;
length = getLength();
width = getWidth();
area = getArea(length, width);
displayData(length, width, area);
}
public static double getLength()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter length. ");
double length = keyboard.nextDouble();
System.out.println("The length is " + length);
return length;
}
public static double getWidth()
{
Scanner keyboard = new Scanner(System.in);
double width;
System.out.println("Enter width. ");
width = keyboard.nextDouble();
System.out.println("The width is " + width);
return width;
}
public static double getArea(double length, double width)
{
double area = length * width;
System.out.println("The area is: " + area);
return area;
}
public static void displayData(double length, double width, double area)
{
System.out.println(" The length is: \t" + length);
System.out.println(" The width is: \t" + width);
System.out.println(" The area is: \t" + area);
}
}

Adding objects with different parameter into the array

So I have this question,
Class circle:
Contains an appropriate attribute to store the radius.
Contains a constructor with one parameter to set the radius.
Contains set and get methods.
Contains a method for calculating the area and another method for calculating the
circumference.
Circle should contain an appropriate attribute to keep track (count) of the number of
Circle objects instantiated.
Class TestCircle:
Create an array of 10 circles of radii 1.0 , 2.0, ..., 10.0.
Print the area and circumference of each circle.
Retrieve and print the number of circles that have been instantiated.
My code is:
public class Circle {
public double radius= 0.0;
public int counter;
public Circle (double radius){
this.radius = radius;
counter++;
}
public Circle (){
}
public void setRadius (double radius){
this.radius = radius;
}
public double getRadius (){
return radius;
}
public double Area (){
return 3.14*radius*radius;
}
public double Circumference (){
return 2*3.14*radius;
}
}
public class TestCircle {
public static void main (String args []){
Circle [] arr = new Circle [10];
System.out.println ("The circumference" + arr.Circumference());
System.out.println ("The area" + arr.Area());
System.out.println ("The number of circles" + arr.counter);
}
}
My question is:
How am I supposed to create 10 circle objects with different radius and add it to the array?
I know that the idea was to add the objects to the array by using the for loop but I couldn't add the radius into the process.
Thank you.
Your code could change like
public class Circle {
private double radius;
private static int numberOfCircles = 0;
public Circle (double radius){
this.radius = radius;
numberOfCircles++;
System.out.println("The circumference : " + getCircumference());
System.out.println("The area : " + getArea());
}
public double getRadius (){
return radius;
}
public double getArea (){
return 3.14*radius*radius;
}
public double getCircumference (){
return 2*3.14*radius;
}
public static int getNumberOfCirclesCreated(){
return numberOfCircles;
}
}
public class TestCircle {
public static void main (String args []) {
Circle [] circles = new Circle [10];
for(int counter=0;counter< circles.length;counter++){
circles[counter]=new Circle((double)(counter+1));
}
System.out.println("Number of circles : " + Circle.getNumberOfCirclesCreated());
}
}
Create for loop that iterates through each array cell. You then create a new Circle object and call its setRadius function. You then set array Cell to equal the Circle object and continue iterating till the array is filled.
Additionally, your counter should be static (as corrected by Fildor). Consider also setting radius as private, seeing as you put in getter/setters.

Why won't my overloaded, static method recognize my height parameter?

So I have three static, overloaded methods that are used in my AreaClient class that are taking input from the user and passing what those inputs are as parameters to the methods below. For some reason though I can't seem to get the last area method to take in my hieght variable as a parameter. I keep getting an error saying "cannot find symbol". These are supposed to be overloaded methods, just what the assignment says. Sorry if this is real simple but I am pretty new to programming. Here is the code that I wrote.
import java.util.Scanner; // Needed for the Scanner class
public class AreaClient {
public static void main(String[] args) {
double circleRadius; //input for radius of circle
int width, length; //input for rectangle width and length
double cylinderRadius, height; //input for radius of a cylinder and hieght
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// gathering input for radius of circle
System.out.println("Enter radius of circle");
circleRadius = keyboard.nextDouble();
// input for width and length of rectangle
System.out.println("Enter width of rectangle");
width = keyboard.nextInt();
System.out.println("Enter length of rectangle");
length = keyboard.nextInt();
// input for radius and hieght of cylinder
System.out.println("Enter radius of cylinder");
cylinderRadius = keyboard.nextDouble();
System.out.println("Enter hieght of cylinder");
height = keyboard.nextDouble();
//returning area methods results and storing them in new variables
double circleArea = area(circleRadius);
int rectangleArea = area(width, length);
double cylinderArea = area(cylinderRadius, height);
//displaying results of methods
System.out.println("The area of your circle is: " + circleArea);
System.out.println("The area of your rectangle is: " + rectangleArea);
System.out.println("The area of your cylinger is: " + cylinderArea);
}
//overloaded methods that take different inputs
public static double area(double r)
{
return 3.14159265359 * Math.pow(r, 2);
}
public static int area(int w, int l)
{
return w * l;
}
//actual method that doesn't recognize h inside
public static double area(double r, double h)
{
return 2*3.14159265359 * Math.pow(r,2) + h (2*3.14159265359*r);
}
}
And the error msg I am getting
AreaClient.java:54: error: cannot find symbol
return 2*3.14159265359 * Math.pow(r,2) + h (2*3.14159265359*r);
^
symbol: method h(double)
location: class AreaClient
1 error
Thanks guys. Any help is much appreciated.
Notice in the error message:
symbol: method h(double)
Why it is looking for a method called h() which accepts a double? Because you're telling it to:
h (2*3.14159265359*r)
h isn't a method, it's just a value. You need to use an operator to connect it to that other value. I think you meant to do this:
h * (2*3.14159265359*r)
I think you mean: h * (2*3.14159265359*r). Without the operator, Java thinks you're trying to call a method named h(double)
return 2*3.14159265359 * Math.pow(r,2) + h * (2*3.14159265359*r);

Categories