Java :calculate the circle diameter and - java

this is a Class about calculating diameter,circumference and area of circle that user enter radius value and it gives him diameter,cirucumf... ,
this is the class code:
package circle;
import java.util.Scanner;
public class Circle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int radius=0;
int diameter;
int circumference ;
int area;
int Pi;
Pi=(int) 3.14;
area = (int) (radius*radius*Pi);
circumference =(int)(radius*2*Pi);
diameter = (int)(radius*2);
System.out.print("Enter radius value:");
radius=input.nextInt();
System.out.printf("area is %d%n" , area);
System.out.printf("diameter is %d%n", diameter);
System.out.printf("circumference is %d%n", environment);
}
}
this is what output gives me :
Enter radius value: (for exmaple) 4
area is 0 // (real value is 50.24)
diameter is 0 // (8)
circumference is 0 //(25.12)
what is the code problem?
or how can i fix it?

You read the radius AFTER computing area/environment(?)/diameter. Furthermore, your values are int variables, which also means that your value for pi is just 3. I suggest you correct the order of the statements, and start using double instead of int.

"environment" will be replaced by "circumference". As your excepted output is decimal value. So use float/double instead of int. In your program you are calculating diameter,circumference and area after initialising the value of radius(radius=0) but before getting the value of radius(radius=4). I have modified your code. It seem help you.
package circle;
import java.util.Scanner;
public class Circle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int radius=0;
float diameter;
double circumference ;
double area;
double Pi;
Pi= 3.14;
System.out.print("Enter radius value:");
radius=input.nextInt();
area = (radius*radius*Pi);
circumference =(radius*2*Pi);
diameter = (radius*2);
System.out.printf("area is " + area);
System.out.printf("\ndiameter is "+ diameter);
System.out.printf("\ncircumference is "+ circumference);
}
}

you are calculating the values area/environment(?)/diameter before getting and initializing the radius input.And at that time the default value for radius is set which is 0. Hence it is giving the results of all the parameters as 0.So you will have to re order your code as below:
System.out.print("Enter radius value:");
radius=input.nextInt();
area = (int) (radius*radius*Pi);
environment=(int)(radius*2*Pi);
diameter = (int)(radius*2);
System.out.printf("area is %d%n" , area);
System.out.printf("diameter is %d%n", diameter);
System.out.printf("environment is %d%n", environment);

Related

Java Box program with multiple methods and constructors

I am a beginner in programming and am having trouble with using constructors, specifically. I have to write a program for one of my labs that must consist only of:
Three instance variables – length, width and height (each of type double)
One instance variables – input (type Scanner) initialized to System.in
Default constructor (no-arg) – initialize all three instance variables to 1
Initial constructor – initialize all three instance variables
Copy constructor – copy Box
inputWidth, inputLength, and inputHeight methods that set the instance variables based on user input have not parameters and do not
return a value.
a displayDimensions method that displays the length X Width X height (separated by “X”) and does not return a value.
a calcVolume method that has no parameters and calculates the volume of the box
We also were given application BoxTest in which the output must
exactly match the following:
Default dimensions are 1.0 X 1.0 X 1.0 with volume of 1.0
Initial dimensions are 8.5 X 11.0 X 1.0 with volume of 93.5
Copied dimensions are 8.5 X 11.0 X 1.0 with volume of 93.5
Update dimensions
Enter length: 1
Enter width: 2
Enter height: 3
Updated dimensions are 1.0 X 2.0 X 3.0 with volume of 6.0
Here's my code:
import java.util.Scanner;
public class Box {
public static void main(String args[]) {
double length, width, height;
Scanner input=new Scanner(System.in);
new Box() { //
Box defaultBox=new Box();
double length = 1.0;
double width = 1.0;
double height = 1.0;
System.out.print("Default dimensions are " + length + " X " + width + " X " + height);
defaultBox.displayDimensions();
System.out.println(" with volume of "+defaultBox.calcVolume());
Box initialBox=new Box(length, width, height);
length = 8.5;
width = 11.0;
height = 1.0;
System.out.print("Initial dimensions are " + length + " X " + width + " X " + height);
initialBox.displayDimensions();
System.out.println(" with volume of "+initialBox.calcVolume());
Box copyBox=new Box(initialBox);
System.out.print("Copied dimensions are " + length + " X " + width + " X " + height);
copyBox.displayDimensions();
System.out.println(" with volume of "+copyBox.calcVolume());
System.out.println("\nUpdate dimensions");
initialBox.inputLength();
initialBox.inputWidth();
initialBox.inputHeight();
System.out.print("Updated dimensions are ");
initialBox.displayDimensions();
System.out.println(" with volume of "+initialBox.calcVolume());
}
double inputLength() {
Scanner input;
double length = input.nextDouble();
}
double inputWidth() {
Scanner input;
double width = input.nextDouble();
}
double inputHeight() {
Scanner input;
double height = input.nextDouble();
}
double displayDimensions(double length, double width, double height) {
Scanner input;
}
double calcVolume() {
}
}
What am I missing? My program will not compile and gives the error message
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error, insert "Identifier (" to complete MethodHeaderName
Syntax error, insert ")" to complete MethodDeclaration
Syntax error, insert ";" to complete MethodDeclaration
Syntax error, insert "}" to complete ClassBody
at Box.main(Box.java:18)
As I said in the comments, you have put everything in main. Don't do that. As it is, your Box class is basically empty, and you are currently almost creating an anonymous sub-class in main. Your directions do not mention a main, but are pretty straight forward. You were supposed to write something like
public class Box {
// Three instance variables – length, width and height (each of type double)
private double length, width, height;
// One instance variables – input (type Scanner) initialized to System.in
private Scanner input = new Scanner(System.in);
// Default constructor (no-arg) – initialize all three instance variables to 1
public Box() {
this.length = this.width = this.height = 1;
}
// Initial constructor – initialize all three instance variables
public Box(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
// Copy constructor – copy Box
public Box(Box b) {
this(b.length, b.width, b.height);
}
// inputWidth, inputLength, and inputHeight methods that set the instance
// variables based on user input have not parameters and do not return a value.
public void inputWidth() {
this.width = input.nextDouble();
}
public void inputLength() {
this.length = input.nextDouble();
}
public void inputHeight() {
this.height = input.nextDouble();
}
// a displayDimensions method that displays the length X Width X height
// (separated by “X”) and does not return a value.
public void displayDimensions() {
System.out.printf("%.2fX%.2fX%.2f%n", length, width, height);
}
// a calcVolume method that has no parameters and calculates the volume of the
// box
public double calcVolume() {
return length * width * height;
}
}
Create a Java class named Package that contains the following:
Package should have three private instance variables of type double named length, width, and height.

How to get the circumference, area and radius of a circle in java?

I'm trying to print out the radius, circumference and area of a circle, and it is not working. I'm a complete beginner at java and coding so thank you for the help.
public class program54c {
public static void main (String args[]) {
double pi = 3.14159;
double radius = 15.337;
double circumference = (2*pi*radius);
double area = (pi*(radius*2));
System.out.println("The radius of the circle" = radius);
System.out.println("The circumference of the circle" = circumference);
System.out.println("The area of the circle" = area);
}
}
Your code seems correct except for one thing (assuming you know your mathematical calculations).
System.out.println("The radius of the circle" = radius);
You are not using the correct string concatenation for your output.
Replace = with + and try. For example,
System.out.println("The radius of the circle " + radius);
In your print statements, you need to use the + operator instead of = to append the variables value to your string. For example
"The area of the circle " = area
should be
"The area of the circle " + area
this will concatenate (append) the value of area to the string "The area of the circle "
Full example below:
public class program54c
{
public static void main (String args[])
{
double pi = 3.14159;
double radius = 15.337;
double circumference = (2*pi*radius);
double area = (pi*(radius*2));
System.out.println("The radius of the circle " + radius);
System.out.println("The circumference of the circle + circumference);
System.out.println("The area of the circle " + area);
}
}
I spot two errors in your code:
The string concatenation, as precised in the others answers, must be done with + and not =.
radius * 2 is not radius² ! You should use Math.pow(radius, 2) or radius*radius.
On a side note, you can use Math.PI instead of your own pi.

Regarding input for creating circles using center coordinates

Hello I was given an assignment in which I have to draw 3 circles using their center coordinates and radii which is input by the user. The assignment specifically states that I must input the center and radius, I cannot input the x and y coordinates separately. They must be input as a coordinate pair (x,y).
Here is my code.
import java.util.*;
import java.awt.*;
public class Circles {
static Scanner CONSOLE = new Scanner(System.in);
public static final int PANEL_HEIGHT = 300;
public static final int PANEL_WIDTH = 400;
public static void main (String [] args) {
DrawingPanel panel = new DrawingPanel (PANEL_HEIGHT,PANEL_WIDTH);
Graphics g = panel.getGraphics();
System.out.println();
System.out.println("Red Circle data");
System.out.println("Input center of Red circle: ");
int center1 = CONSOLE.nextInt();
System.out.println("Input radius of Red circle: ");
int radius1 = CONSOLE.nextInt();
System.out.println();
System.out.println("Blue Circle data");
System.out.println("Input center of Blue circle: ");
int center2 = CONSOLE.nextInt();
System.out.println("Input radius of Blue circle: ");
int radius2 = CONSOLE.nextInt();
System.out.println();
System.out.println("Green Circle data");
System.out.println("Input center of Green circle: ");
int center3 = CONSOLE.nextInt();
System.out.println("Input radius of Green circle: ");
int radius3 = CONSOLE.nextInt();
g.setColor(Color.RED);
g.fillOval(center1 -radius1 ,center1-radius1 ,radius1 ,radius1);
g.setColor(Color.BLUE);
g.fillOval(center2 -radius2 ,center2-radius2 ,radius2 ,radius2);
g.setColor(Color.GREEN);
g.fillOval(center3 -radius3 ,center3-radius3 ,radius3 ,radius3);
}
}
My problem is that I don't know how to properly input and store the x and y coordinates as one int. As it is currently it just takes one data point, stores it, and uses it as both x and y.
System.out.println("Red Circle data");
System.out.println("Input center of Red circle: ");
int center1 = CONSOLE.nextInt();
Here is where I know java must ask for the values and store them.
g.setColor(Color.RED);
g.fillOval(center1(THIS SHOULD BE THE X VALUE) -radius1 ,center1(THIS SHOULD BE THE Y VALUE)-radius1 ,radius1 ,radius1);
Then here I have to somehow get the values stored in the above code.
Please help i'm kinda new to this and would appreciate some feedback! Hope what im asking for makes sense! :S
not JAVA coder so I stick to C++, are you sure you want x,y pair in single int ?
1.If yes then just encode it
but you must know the coordinates range
for example if you have 32bit int and your coordinates fits to 16 bit then:
int xy,x,y;
xy = (x&0x0000FFFF) | ((y&0x0000FFFF)<<16); // this makes xy = (x,y)
and if you need to unpack the data again do:
x= xy &0x0000FFFF; if (int(x&00008000)!=0) x|=0xFFFF0000;
y=(xy>>16)&0x0000FFFF; if (int(y&00008000)!=0) y|=0xFFFF0000;
the if at the end restores the missing bits for negative numbers ...
2.if in single variable instead then use
array:
int xy[2],x,y;
xy[0]=x;
xy[1]=y;
or struct/class
int x,y;
struct point { int x,y; } xy;
xy.x=x;
xy.y=y;

how do I get the output answer 4 decimal places

I need to round the outputs to 4 decimal places but I am not quite sure on how to do that my thing runs exactly how I want it too just need to round off the last decimals off too 4 places
import java.util.Scanner; //Needed for the Scanner class
public class SphereCalculations
{
public static void main(String[] args) //all the action happens here!
{ Scanner input = new Scanner (System.in);
double radius;
double volume;
double surfaceArea;
System.out.println("Welcome to the Sphere Calculator. ");
System.out.print( "Enter radius of sphere: " );
radius = input.nextDouble();
volume = ((4.0 / 3.0) * (Math.PI * Math.pow(radius, 3)));
surfaceArea = 4 * (Math.PI * Math.pow(radius, 2));
System.out.println("The Results are: ");
System.out.println("Radius: " + radius);
System.out.println("Sphere volume is: " + volume);
System.out.println("Sphere Surface Area is: " + surfaceArea);
}
}
Output:
Radius: 7.5
Volume: 1767.1459
Surface Area: 706.8583
System.out.printf("Sphere Surface Area is: %.4f%n", surfaceArea);
If you find that you need more control, you can use DecimalFormat which has many more formatting options. This is especially helpful if you want to print out a double in scientific notation.
//specify a number locale, some countries use other symbols for the decimal mark
NumberFormat f = NumberFormat.getInstance(Locale.ENGLISH);
if(f instanceof DecimalFormat) {
DecimalFormat d = (DecimalFormat) f;
d.applyPattern("#.0000"); //zeros are non optional, use # instead if you don't want that
System.out.println(d.format(surfaceArea));
}

Variables from the main class to be assigned to variables in the subclasses - beginner

I have this code which will find the area of different shapes depending on the inputted shape of the user. The problem is how can I get the inputted measurements(e.g. length, width) from the main class to the Circle, triangle, rectangle and square classes? here's my code.
import java.lang.Math;
import java.util.Scanner;
import java.text.DecimalFormat;
class Circle{
double radius;
void CircleMeasurement(){
radius = r;
}
double getCircleArea(){
return(Math.PI*Math.pow(radius,2));
}
}
class Triangle{
int base, height;
void TriangleMeasurement(){
base = b;
height = h;
}
int getTriangleArea(){
return((base*height)/2);
}
}
class Rectangle{
int length, width;
void RectangleMeasurement(){
length = l;
width = w;
}
int getRectangleArea(){
return(length*width);
}
}
class Square{
int sides;
void SquareMeasurement(){
sides = s;
}
int getSquareArea(){
return( sides * sides);
}
}
class Shapes{
public static void main(String[] args){
String key;
double r;
int b, h, l, w, s;
System.out.println("Welcome!");
System.out.println("Choose your option:");
System.out.println("1 - Circle, 2 - Triangle, 3 - Rectangle, 4 - Square");
Scanner in = new Scanner(System.in);
key = in.nextLine();
if (key=="1" || key =="circle"){
System.out.println("Area for Circle");
System.out.println("Enter radius:");
Scanner.in = new Scanner(System.in);
r = in.nextInt;
Circle circle1 = new Circle();
System.out.println("The area is equal to" + circle1.getCircleArea());
}
else if (key == "2"){
System.out.println("Area for Triangle");
System.out.println("Enter base:");
Scanner.in = new Scanner(System.in);
b = in.nextInt;
System.out.println("Enter height:");
h = in.nextInt;
Triangle triangle1 = new Triangle();
System.out.println("The area is equal to" + triangle1.getTriangleArea());
}
else if (key == "3"){
System.out.println("Area for Rectangle");
System.out.println("Enter length:");
Scanner.in = new Scanner(System.in);
l = in.nextInt;
System.out.println("Enter width:");
w = in.nextInt;
Rectangle rectangle1 = new Rectangle();
System.out.println("The area is equal to" + rectangle1.getRectangleArea());
}
else if (key == "4"){
System.out.println("Area for Square");
System.out.println("Enter side:");
Scanner.in = new Scanner(System.in);
s = in.nextInt;
Square square1 = new Square();
System.out.println("The area is equal to" + square1.getSquareArea());
}
}
}
You can set the appropriate variables at the time of Object creation using constructor.
Circle(int r){
radius = r;
}
Rectangle(int l, int b){
length = l;
breadth = b;
}
Circle c = new Circle(9); //creates a new Circle with radius 9
Rectangle r = new Rectangle(2,3) //Creates a new Rectangle with length as 2, breadth as 3
That said, you can also use setter methods.
Also, using == to compare Strings is frowned upon and often will give you wrong results. Use
.equals() instead.
"Circle".equals(input);
Two things to mention here:
Pass the values taken from scanner to classes as argument to method or constructor. So it can be used by method for furthur calculations. Also using inheritance here will be a good option.
Never use == for string comparision. It will not work, use .equals instead.
One of the problem in your code is that you are comparing string using ==. Strings should be compared using equals method.
change such statements
if (key=="1" || key =="circle"){
to
if (key.equals("1") || key.equals("circle")){
The other problem is that you have not defined constructors with proper arguemnts in your classes such as Circle, Triangle etc. As you are not setting the proper attributes so calling the methods will not provide you the correct results.
For example you need to have constructor in Circle class,to initialize the radius param:
public Circle(int r) {
radius = r;
}
And creating the object of Circle like this, followed by call to getCircleArea should give u the desired result:
Circle circle1 = new Circle(r);
System.out.println("The area is equal to" + circle1.getCircleArea());
You can set values of variables in several ways. First way it's constructor, see rocketboy answer. Second one it's mark your variables as private and use mutator methods. It's recomended way/ See example below:
class Circle{
private double radius;
Circle(double radius){
this.radius = radius;
}
public void setRadius(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
Firs you should create getters and setters.Then
class Circle{
double radius;
public double getRadius(){
return radius;
}
public void setRadius(double r){
radius=r;
}
void CircleMeasurement(){
radius = r;
}
....
r = in.nextInt;
Circle circle1 = new Circle();
circle1.setRadious(r);

Categories

Resources