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().
Related
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);
}
}
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.
I'm supposed to be using a constructor to accept the radius of a circle as an argument then using various accessor and mutator methods to display the area, circumference, and diameter. When I input the value for radius, say 4, it says that the radius and all other values (area, circumference, diameter ) are 0.0. I'm new to java and wanna know what I'm missing.
// import scanner to read keyboard input
import java.util.Scanner;
class CircleCalculator
{
private double radius;
public CircleCalculator(double r)
{
radius = r;
}
public static void main(String[] args)
{
// declare the variable keyboard that can reference an object of the scanner class
// create a new Scanner object in the memory that reads from the input System.in
Scanner keyboard = new Scanner(System.in);
System.out.println("\nWelcome to Cam's Magic Circle Calculator!");
System.out.println("\nEnter the radius of your circle");
double r, a, d, c;
CircleData circledata = new CircleData();
System.out.println("\nThe measurements of a circle with the radius " + circledata.getRadius() + " are:\n" +
"\tArea: " + circledata.getArea() +" units squared\n" +
"\tDiameter: " + circledata.getDiameter() +" units\n" +
"\tCircumference: " + circledata.getCircumference() +" units\n");
}
public static class CircleData //create class for mutator and accessor methods
{
Scanner keyboard = new Scanner(System.in);
double r = keyboard.nextDouble();
CircleCalculator setRadius = new CircleCalculator(r);
final double pi = 3.1415;
private double radius, area, diameter, circumference;
private double getRadius()
{
return radius;
}
private double getArea()
{
area = pi * radius * radius;
return area;
}
private double getDiameter()
{
diameter = 2 * radius;
return diameter;
}
private double getCircumference()
{
circumference = 2 * pi * radius;
return circumference;
}
}
}
Gives:
Welcome to Cam's Magic Circle Calculator!
Enter the radius of your circle
4
The measurements of a circle with the radius 0.0 are:
Area: 0.0 units squared
Diameter: 0.0 units
Circumference: 0.0 units
Your current code is confused because of the nesting of your classes. I recommend following good code practices by separating them out into their own class files. Let CircleData handle the actual circle data and calculation and make CircleCalculator your overall program sequence logic.
CircleCalculator
import java.util.Scanner;
public class CircleCalculator
{
public static void main(String[] args)
{
System.out.println("\nWelcome to Cam's Magic Circle Calculator!");
System.out.println("\nEnter the radius of your circle");
Scanner keyboard = new Scanner(System.in);
CircleData circledata = new CircleData(keyboard.nextDouble());
keyboard.close();
System.out.println("\nThe measurements of a circle with the radius " + circledata.getRadius() + " are:\n" +
"\tArea: " + circledata.getArea() +" units squared\n" +
"\tDiameter: " + circledata.getDiameter() +" units\n" +
"\tCircumference: " + circledata.getCircumference() +" units\n");
}
}
CircleData (in separate file so methods are now public)
public class CircleData
{
final double pi = 3.1415;
private double radius, area, diameter, circumference;
public CircleData(double radius) {
this.radius = radius;
}
public double getRadius()
{
return radius;
}
public double getArea()
{
area = pi * radius * radius;
return area;
}
public double getDiameter()
{
diameter = 2 * radius;
return diameter;
}
public double getCircumference()
{
circumference = 2 * pi * radius;
return circumference;
}
}
Because radius fields from CircleCalculator and CircleData classes are two different fields. So, you cannot use the radius of CircleCalculator from CircleData because CircleData contains such field already.
CircleData actually shouldn't have the Scanner field, it breaks SRP https://en.wikipedia.org/wiki/Single-responsibility_principle.
I'd recommend writing it this way:
class CircleCalculator {
public static void main(String[] args) {
// declare the variable keyboard that can reference an object of the scanner class
// create a new Scanner object in the memory that reads from the input System.in
Scanner keyboard = new Scanner(System.in);
System.out.println("\nWelcome to Cam's Magic Circle Calculator!");
System.out.println("\nEnter the radius of your circle");
CircleData circledata = new CircleData(keyboard.nextDouble());
System.out.println("\nThe measurements of a circle with the radius " + circledata.getRadius() + " are:\n" +
"\tArea: " + circledata.getArea() + " units squared\n" +
"\tDiameter: " + circledata.getDiameter() + " units\n" +
"\tCircumference: " + circledata.getCircumference() + " units\n");
}
public static class CircleData //create class for mutator and accessor methods
{
final double pi = 3.1415;
private final double radius;
public CircleData(double radius) {
this.radius = radius;
}
private double getRadius() {
return radius;
}
private double getArea() {
return pi * radius * radius;
}
private double getDiameter() {
return 2 * radius;
}
private double getCircumference() {
return 2 * pi * radius;
}
}
}
The radius variable isn't being passed from constructor because you have defined the constructor in the CircleCalculator class but the methods for calculating the area, circumference, etc using the radius variable value are in different class.
CircleCalculator setRadius = new CircleCalculator(r);
Here, though setRadius has the value which user has entered but it's not being used.
CircleData circledata = new CircleData();
Here, the circledata is referencing nothing. The method calls
circledata.getRadius() , circledata.getArea() , circledata.getDiameter() , circledata.getCircumference() are actually returning the default value of double that is 0.0 because the radius variable default value is 0.0
Also, there should be only one public class in a class file whose name should match the class file name and that public class should have the public static void main(String[] args) method.
I know that these types of questions get asked a lot and I've read
this one
and
this one
but for some reason I'm still having troubles understand the issue my current program is having.
I'm trying to create a set of classes that defines a series of 3-D shapes that can store its size, and provides access to change the data. It should also be able to calculate circumference, area, and volume. I've only gotten to the point where I'm doing my first chosen shape (a sphere) and I'm getting this error in the println inside the if statement.
import java.util.Scanner;
public class Shapes
{
public static void main(String[] args)
{
String input;
double Radius;
Scanner scan = new Scanner(System.in);
System.out.println("Choose a shape. 'S' for sphere, 'P' for pyramid, 'C' for cone: ");
input = scan.next();
if (input.equals("S"))
{
System.out.println("Enter radius: ");
Radius = scan.nextDouble();
Sphere calcCircumference;
Sphere calcArea;
Sphere calcVolume;
System.out.println("The circumference is "+Sphere.circumference+", the area is "+Sphere.area+", the volume is "+Sphere.volume+".");
}
}
}
public class Sphere
{
// instance variables
protected double radius;
protected double circumference;
protected double area;
protected double volume;
Scanner scan = new Scanner(System.in);
/**
* Constructor for objects of class Sphere
*/
public Sphere()
{
// initialise instance variables
radius = 0;
circumference = 0;
area = 0;
volume = 0;
}
/**
*Gets user entered radius
*/
public double getRadius(double Radius)
{
radius = radius;
return radius;
}
public double calcCircumference()
{
circumference = 2*Math.PI*radius;
return circumference;
}
public double calcArea()
{
area = 4*Math.PI*Math.pow(radius,2);
return area;
}
public double calcVolume()
{
volume = (4*Math.PI*Math.pow(radius,3))/3;
return volume;
}
}
Any help or guidance would be appreciated.
System.out.println("The circumference is "+Sphere.circumference+", the area is "+Sphere.area+", the volume is "+Sphere.volume+".");
You need to create an instance of Sphere before you can access it fields.
Sphere sphere = new Sphere();
You then need to provide the information that the object needs
sphere.radius = Radius; // I'd prefer a setter method
Then you can make use of the information that this instance provides...
System.out.println("The circumference is "+sphere.calcCircumference()+", the area is "+Sphere.calcArea()+", the volume is "+Sphere.calcVolume()+".");
There is no need to keep track of circumference, area or volume, they are calculated fields, you simply need to call the methods you need to get the calculated result.
The fields circumference, area, volume and radius are known as instance fields, they require an instance of the class before you can use them. This means you can have multiple instances of Sphere each with there own unquie values
You might like to take a closer look at Classes and Objects
I changed your code a bit, now it is working (may not be the most efficient way):
import java.util.Scanner;
public class Shapes {
public static void main(String[] args) {
String input;
double Radius;
Scanner scan = new Scanner(System.in);
System.out
.println("Choose a shape. 'S' for sphere, 'P' for pyramid, 'C' for cone: ");
input = scan.next();
if (input.equals("S")) {
System.out.println("Enter radius: ");
Radius = scan.nextDouble();
Sphere calcCircumference;
Sphere calcArea;
Sphere calcVolume;
System.out.println("The circumference is " + Sphere.circumference
+ ", the area is " + Sphere.area + ", the volume is "
+ Sphere.volume + ".");
}
}
public static class Sphere {
// instance variables
protected double radius;
protected static double circumference;
protected static double area;
protected static double volume;
Scanner scan = new Scanner(System.in);
/**
* Constructor for objects of class Sphere
*/
public Sphere() {
// initialise instance variables
radius = 0;
circumference = 0;
area = 0;
volume = 0;
}
/**
* Gets user entered radius
*/
public double getRadius(double Radius) {
radius = radius;
return radius;
}
public double calcCircumference() {
circumference = 2 * Math.PI * radius;
return circumference;
}
public double calcArea() {
area = 4 * Math.PI * Math.pow(radius, 2);
return area;
}
public double calcVolume() {
volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;
return volume;
}
}
}
As a new student to Java I have bean practicing writing methods and then calling them from a different class. I would like to know how to have the radius determined by user input. I understand I need to use the Scanner class but I'm not sure which class to import the Scanner in and where to put the following bit of code.
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
FIRST FILE - My Methods
package circle;
public class Circle {
private double radius;
final double pi;
public Circle(double radiusIn, double piIn) {
radius = radiusIn;
pi = piIn;
}
public double getRadius() {
return radius;
}
public double calculateDiameter() {
return radius + radius;
}
public double calculateCircumference() {
return 2 * pi * radius;
}
public double calculateArea() {
return pi * radius * radius;
}
}
SECOND FILE
package circle;
public class CircleTest {
public static void main(String[] args) {
Circle myCircle;
myCircle = new Circle(3, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
}
Typically you declare variables where you need them in this case that means in the main method where the rest of the user interaction takes place.
package circle;
public class CircleTest {
public static void main(String[] args) {
Circle myCircle;
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
myCircle = new Circle(radius);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
}
Also Math.PI is a much more accurate approximation of pi. Use that instead of relying on the user to pass in the correct value:
package circle;
public class Circle {
private double radius;
public Circle(double radiusIn) {
radius = radiusIn;
}
public double getRadius() {
return radius;
}
public double calculateDiameter() {
return radius + radius;
}
public double calculateCircumference() {
return 2 * Math.PI * radius;
}
public double calculateArea() {
return Math.PI * radius * radius;
}
}
Think of an Object as an object, like an apple or a toothbrush.
class Circle is a defintion of an Object; it's a description that attempts to match reality. The predefined Java Object is like anything you might find in reality, you can't call eat() on an Object (in the real world) because it might be an apple, but it might be a toothbrush (or a circle).
Therefore, place the code where it makes sense as if it were a real world object. You want to retrieve user input. Does a circle know how to read user input? No!
You call your other class CircleTest. But what it really is, is CircleCreationApplication; that might be a better name for it. In an application that creates circles, you would receive user input. So that is where the code can go. Once you have your user input, you can use that to create the circle.
package circle;
public class CircleCreationApplication {
public static void main(String[] args) {
Circle myCircle;
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
myCircle = new Circle(radius, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
userInput.close();
}
}
Note: #ratchetfreak's answer has some other good things. Please read that as well
I think the user interaction code goes into the main class. That's where you handle the workflow, depending on user input. What you actually want is to remove the hardcoded radius (3) and read the value from the user using the Scanner, right?
Then your code snippet goes in the main method, right before instantiating the Circle object.
public static void main(String [] args)
{
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
Circle myCircle;
myCircle = new Circle(radius, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter ());
System.out.println("Circle circumference is " + myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
You would want to import the scanner and add the code to the second file. Then you can use radius as argument to the Circle constructor instead of just 3.