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);
}
}
Related
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 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.
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.
When I try to run this bit of code that I wrote:
import java.util.Scanner;
public class F1Calc
{
public static void main(String args[])
{
System.out.println("The coefficient of friction of the " + getSurface() + " surface is " + getCoeff() + ". The mass of the ball was " + getMass() + " and the momentum of the ball was "+ getMomentum() + " Nm. The potential energy contained by the ball at the top of the .121 m high ramp was " + getPotEnergy() + " Joules.");
}
public static String getSurface()
{
Scanner kb = new Scanner(System.in);
System.out.println("What is the surface you are rolling the ball into?");
String surface = kb.nextLine();
kb.close();
return surface;
}
public static double getMass()
{
Scanner kb2 = new Scanner(System.in);
System.out.println("What is the mass of the ball in kilograms?");
double mass = kb2.nextInt();
kb2.close();
return mass;
}
public static double getPotEnergy()
{
double potEnergy = getMass() * .121 * 9.8;
return potEnergy;
}
public static double getMomentum()
{
double doublePE = 2 * getPotEnergy();
double doublePEOverMass = doublePE / getMass();
double velocity = Math.sqrt(doublePEOverMass);
double momentum = velocity * getMass();
return momentum;
}
public static double getCoeff()
{
double coeff = getPotEnergy() / (getMass() * 9.8);
return coeff;
}
}
The following is displayed on the console:
What is the surface you are rolling the ball into?
Tile
What is the mass of the ball in kilograms?
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at F1Calc.getMass(F1Calc.java:20)
at F1Calc.getPotEnergy(F1Calc.java:26)
at F1Calc.getCoeff(F1Calc.java:39)
at F1Calc.main(F1Calc.java:6)
Adding lines so that my post can be submitted. Adding lines so that my post can be submitted. Adding lines so that my post can be submitted. Adding lines so that my post can be submitted.
There is only one underlying InputStream used for Scanner so don't close it - doing so closes it for all future instances of the class making it impossible to read from the source
You do not want to open a new scanner and close it each time. Instead, just create it once.
I also fixed two other bugs in your code.
You were using nextInt() to read a double. This has been replaced with nextDouble().
You are asking the user to input mass multiple times. This has been fixed by caching the value of mass, so it is read from the user only once.
Here is the corrected code.
import java.util.Scanner;
public class F1Calc
{
// Cache the values so we don't have to keep bugging the user
static double mass;
static Scanner kb;
public static void main(String args[])
{
mass = -1;
kb = new Scanner(System.in);
System.out.println("The coefficient of friction of the " + getSurface() + " surface is " + getCoeff() + ". The mass of the ball was " + getMass() + " and the momentum of the ball was "+ getMomentum() + " Nm. The potential energy contained by the ball at the top of the .121 m high ramp was " + getPotEnergy() + " Joules.");
}
public static String getSurface()
{
System.out.println("What is the surface you are rolling the ball into?");
String surface = kb.nextLine();
return surface;
}
public static double getMass()
{
if (mass > 0) return mass;
System.out.println("What is the mass of the ball in kilograms?");
mass = kb.nextDouble();
return mass;
}
public static double getPotEnergy()
{
double potEnergy = getMass() * .121 * 9.8;
return potEnergy;
}
public static double getMomentum()
{
double doublePE = 2 * getPotEnergy();
double doublePEOverMass = doublePE / getMass();
double velocity = Math.sqrt(doublePEOverMass);
double momentum = velocity * getMass();
return momentum;
}
public static double getCoeff()
{
double coeff = getPotEnergy() / (getMass() * 9.8);
return coeff;
}
}