Where to put Scanner class - java

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.

Related

Radius Variable Isn't Being Passed From Constructor

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.

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().

Asking for user input with java setters and getters

how would i ask the user for the radius? I'm pretty sure it will be an easy fix but i'm just not sure how to do it. Here is my code so far.
import java.util.Scanner;
public class CircleDriver
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Circle circle1 = new Circle();
circle1.setRadius(20);
System.out.println("Enter the radius of a circle " + circle1.getRadius());
System.out.println("Area = " + circle1.calculateArea());
System.out.println("Diameter = " + circle1.calculateDiameter());
System.out.println("Circumference = " + circle1.calculateCircumference());
}
}
Circle class :
public class Circle
{
private double radius;
private final double PI = 3.14159;
/**
* this method calculates the area of the given radius
* #return
*/
public double calculateArea() {
double area;
area = (PI * radius * radius);
return area;
}
/**
* this method calculates the diameter of the given radius
* #return
*/
public double calculateDiameter() {
double diameter;
diameter = (radius * 2);
return diameter;
}
/**
* this method calculates the circumference of the given radius
* #return
*/
public double calculateCircumference() {
double circumference;
circumference = (2 * PI * radius);
return circumference;
}
/**
* this method sets the radius of the object
* #param radius
*/
public void setRadius(double radius) {
this.radius = radius;
}
/**
* this radius returns the radius given
* #return
*/
public double getRadius() {
return radius;
}
}
Try this :
System.out.println("Enter the radius pls :");
try {
circle1.setRadius(input.nextDouble());
} catch (InputMismatchException e){
System.out.println("ERROR : Invalid input !");
}
You're creating a Scanner called input, but you're not using it. Instead, you're hard-coding the value 20.
Try this:
Scanner input = new Scanner(System.in);
Circle circle1 = new Circle();
System.out.print("Enter the radius of a circle: ");
circle1.setRadius(input.nextDouble());
System.out.println("Area = " + circle1.calculateArea());
System.out.println("Diameter = " + circle1.calculateDiameter());
System.out.println("Circumference = " + circle1.calculateCircumference());
Scanner input = new Scanner(System.in);
Circle circle1 = new Circle();
System.out.println("Enter the radius of a circle ");
int radius = input.nextInt();
There are several ways in getting an input from the user including BufferedReader, Console, Scanner etc. Above is an example using Scanner class. Now use the above radius value in your further calculations.

non-static variable cannot be referenced from a static context in println statement

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

Compute Area of a circle

My program runs and after a few secs it just stops compiling. tried to assign input for the radius and it didn't worked. Would appreciate it if somebody can help me with explaining why my program fails to run.
package computearea;
import java.util.Scanner;
public class ComputeArea {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double radius = input.nextDouble();
System.out.println("Radius: " + radius);
double area;
area = radius* radius * 3.14159;
System.out.println("The area for the circle of radius " + radius + "is"
+ area);
}
}

Categories

Resources