I'm really new to Java and I know I messed up bad somewhere on this program. Every time I try and fix it now, I make it worse. What I'm trying to do is create a basic program to calculate radius, diameter, and circumference of a circle. The code must include a method of printCircleInfo() for the output and must declare and use a no argument constructor to input data for the calculations. I'm totally off track with this I think, but this is what I've managed to do:
import java.util.Scanner;
public class Circle4
{
public static float PI; // PI.
public static float radius; // Radius of a circle
public static double dia; // Diameter of the circle
public static double area; // Area of the circle
public Circle4()
{
//Calculations
dia = radius*2; // Diameter calculation.
circ = PI*(radius*2); // Circumference calculation.
area = PI*(radius*radius); // Area calculation.
PI = 3.14159f;
Scanner in;
in = new Scanner(System.in); // Input Scanner
System.out.println("Enter the radius of the circle: "); //prompt for radius of the circle
radius = in.nextFloat();
}
public static void printCircleInfo()
{
System.out.println("The diameter of the cicle is " + dia); // Output of Diameter.
System.out.println("The circumferance of the circle is " + circ); // Output of Circumference.
System.out.println("The area of the circle is " + area); // Output of Area.
}
public static void main (String[] args)
{
circle = circleData;
circleData = Circle4();
print = printCircle;
printCircle = printCircleInfo();
}
}
I have worked myself into such confusion that I don't even know where to begin to fix it now. Thank you so much.
Some issues here:
(1)
public static void main (String[] args)
{
circle = circleData;
circleData = Circle4();
print = printCircle;
printCircle = printCircleInfo();
}
In java you should declare what type each variable is of. You will get compilation error from this code
(2)
You are declaring your fields [such as radius, area..] as static, and initialize them in constructor - I doubt that this is what you want. Note that static fields are shared among all instances of this class.
There are more issues with this code. Try to compile it. Your compiler will tell you what's wrong [at least for compile time errors]. fix the mistakes, and re-compile.
Related
I want my program to display the area of square and rectangle, as you might have already guessed this is a homework problem so I cant really change the format.
import java.util.*;
abstract class Shape
{
int area;
abstract void area();
}
class Square extends Shape
{
int len;
void area()
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the lenght of the square: ");
len=s.nextInt();
}
public void displayarea()
{
Square q= new Square();
q.area();
System.out.println("The area of the square is: "+(len*len));
}
}
class Rectangle extends Shape
{
int l,b;
public void area()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the lenght of the rectangle: ");
l=sc.nextInt();
System.out.println("Enter the breadth of the rectangle: ");
b=sc.nextInt();
}
public void displayarea()
{
Rectangle r = new Rectangle();
r.area();
System.out.println("The area of the rectangle is: "+(l*b));
}
}
public class Postlab
{
public static void main(String[] args)
{
Rectangle rectangle = new Rectangle();
Square square = new Square();
rectangle.displayarea();
square.displayarea();
}
}
The problem is that you are calling area on the wrong object.
public void displayarea() {
Square q = new Square();
q.area();
System.out.println("The area of the square is: " + (len * len));
}
When you call this on a square A it first creates a square B and calls B.area(). Because of this when you reach area calculation, result is 0. All values are set on square B while values of square A remain unset.
Instead you want to call area on your square A. Like this.
public void displayarea() {
area();
System.out.println("The area of the square is: " + (len * len));
}
In your code displayarea() method, you are creating new Object of Class (Square/Rectangular) to call area() method. So the objects to which scanner is assigning values in using area() method is different to which you are printing the area. So technically area() and displayarea() are being called on different objects of class. So you are always getting null or 0. Data assigned in one object is not shared by another objects. (until the variables are not declared as static, static variables shared between all instance of class)
So your code should be updated as below(same applied to Rectangle):
public void displayarea() {
area();
System.out.println("The area of the square is: " + (len * len));
}
I am working on using separate classes in a program in Object-Oriented Programming. Warning: I am HORRID at OOP, so if my questions are stupid and nonsensical, please tell me or, if you know what I mean, edit my post for me.
Would you create the separate class and the program itself in separate .java files or the same*?
*Same, as in
public class filename
{
// ... content
}
class name
{
}
Can you use Scanner within the separate class, or should you use it in main() method? If so, how?
Suppose you have to use Scanner in main() method, and you declared a new variable input and initialized it as the Scanner input. How would you set that as one of the variables in the separate class? Would you make a new object and do...
Example:
public class TestSimpleCircle {
public static void main(String[] args {
SimpleCircle circle1 = new SimpleCircle();
System.out.println("The area of the circle of radius " + circle1.radius + " is " + circle1.getArea());
// Create a circle with radius 25
SimpleCircle circle2 = new SimpleCircle(25); System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());
// Create a circle with radius 125
SimpleCircle circle3 = new SimpleCircle(125); System.out.println("The area of the circle of radius " + circle3.radius + " is " + circle3.getArea());
// Modify circle radius
circle2.radius = 100; // or circle2.setRadius(100) System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());
}
}
class SimpleCircle {
double radius;
SimpleCircle() {
radius = 1;
}
SimpleCircle(double newRadius) {
radius = newRadius;
}
double getArea() {
return radius * radius * Math.PI;
}
double getPerimeter() {
return 2 * radius * Math.PI;
}
void setRadius(double newRadius) {
radius = newRadius;
}
}
...that (e.g. circle1.getArea())?
When you create variables in a separate class, are they in any way connected to variables with the same name in the main() method or a different class?
Would you create the separate class and the program itself in separate
.java files or the same*?
Every class in Java should be in its own file but you can create more than one class in one file. For example
class A{
public A(){
System.out.println("A created");
}
}
public class Main {
public static void main(String[] args) {
A x = new A();
}
}
Can you use Scanner within the separate class, or should you use it in
main() method? If so, how?
Depending on your application. Many would prefer organization and separation as much as possible so the top advice is to make it in its own class. But for very simple samples and applications I just throw it in the main() method or if I would use only once in any method. Scanner is class on its own so if you will create another class just to wrap it only alone, it really not worth it at all.
You can create Scanner as member variable of any class and use it if there are some methods you would use with it.
These just some ideas, totally depends on your design, application behavior and personal recommendation
As for how, here is an example
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int number = sc.nextInt();
System.out.println("You entered number " + number);
}
}
Suppose you have to use Scanner in main() method, and you declared a
new variable input and initialized it as the Scanner input. How would
you set that as one of the variables in the separate class? Would you
make a new object and do...
Yes I would make new object of that class and initialize its members with the input value. Or i put the Scanner inside the class to ask about radius of every object created with constructor with no parameters. There are many different approaches and no right or wrong about any of them. Just avoid duplication and dependency as much as possible.
Here is your code edited with example of doing such that
import java.util.Scanner;
public class TestSimpleCircle {
public static void main(String[] args) {
System.out.println("Enter radius of your choice please");
Scanner sc = new Scanner(System.in);
SimpleCircle circle1 = new SimpleCircle(sc.nextInt()); // taking the radius as input
System.out.println("The area of the circle of radius " + circle1.radius + " is " + circle1.getArea());
// Create a circle with radius 25
SimpleCircle circle2 = new SimpleCircle(25);
System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());
// Create a circle with radius 125
SimpleCircle circle3 = new SimpleCircle(125);
System.out.println("The area of the circle of radius " + circle3.radius + " is " + circle3.getArea());
// Modify circle radius
circle2.radius = 100;
System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());
}
}
class SimpleCircle {
double radius;
SimpleCircle() {
radius = 1;
}
SimpleCircle(double newRadius) {
radius = newRadius;
}
double getArea() {
return radius * radius * Math.PI;
}
double getPerimeter() {
return 2 * radius * Math.PI;
}
void setRadius(double newRadius) {
radius = newRadius;
}
}
Scanner just like any other object, can be passed by reference into another method/class and still be used.
A different instance of the scanner class can be created and also used.
You would use Scanner in whichever class you needed it in. If you create a new instance of the object, it will not be connected with the other instance. This question isn't specific to Scanner, but as java Objects in general.
For the 1st question. yes,you can create different classes in the same java file,
after compilation of the java file, separate .class files will be created for each class that you have defined.
i would like to mention that you can save your java file by any name and then compile it.but if any class is declared as public (as in the above example public class filename) then the java file should have the same name as that of the public class.
On not doing so.You will get compile time error saying:
class filename is public ,should be declared in a file named filename.
Hope this helps you a little...
One class - one file. No exception. This will save a huge time when maintain product in future.
class SimpleCircle {
// be private - accessible only inside class
// be final - assign only in constructor
private final double radius;
SimpleCircle(double newRadius) {
radius = newRadius;
}
double area() {
return radius * radius * Math.PI;
}
double perimeter() {
return 2 * radius * Math.PI;
}
}
try to avoid Constructors with useless assignments (what sense default radius=1 if you youse Constructor without parameters). Try to avoid change class state via setters. Create new objects with new state (radius).
Try to call methods nouns, that reflect the returned entity
Try to name void methods verbs, that reflect object behavior.
Now about Scanner.
try to use this idea/template
public class MyClass {
private final Scanner scanner;
public MyClass(Scanner scanner) {
this.scanner = scanner;
}
public void any_work() {
...
int readed = scanner.nextInt();
...
}
}
public class Main {
public static void main(String[] args) {
...
MyClass myClass = new MyClass(new Scanner(System.in));
...
myClass.any_work();
...
}
}
When you create variables in a separate class, are they in any way
connected to variables with the same name in the main() method or a
different class?
Only one way. by method or constructor parameters. See previous code with Main/MyClass.
I'm having difficulty trying to print the result of the static method calcArea, which takes the int radius as parameter to calculate the area of a circle and returns the area.
Here's the code below 👇 Any help would be appreciated.
public class CircleArea {
public int radius;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the radius of the circle: ");
int radius = input.nextInt();
System.out.print("The area of the circle is:" + calcArea()); <-- ERROR HERE
}
public static double calcArea(int radius){
double area = Math.PI * Math.pow(radius, 2);
return area;
}
}
Your call to calcArea needs a parameter passed in. Probably calcArea(radius).
The function calcArea() takes the value of radius and then returns area. To do this, you need to pass an argument to calcArea(). So, your code should be like this:
System.out.print("The area of the circle is:" + calcArea(radius));
The error you're getting clearly points out that you're missing an argument.
call method calcArea, you need give a parameter,Here are the correct example"
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the radius of the circle: ");
int radius = input.nextInt();
System.out.print("The area of the circle is:" + calcArea(radius));
}
Basically, there are two classes... One is supposed to work out the area of a circle, the other is for the user to enter the number of circles they want to work with, the radius of each circle and the program is then to display it after each other. At the end, the biggest area is displayed. It displays an error that the method in the first class cannot be applied to the given types...
The first class:
public class Prac4 {
private float radius;
public Prac4() {
}
public void setRadius(float radius) {
this.radius = radius;
}
public float getRadius() {
return radius;
}
public double calcArea() { //Getting errors if I don't use double
return 3.14* radius*radius; //Getting errors if I try to use pow function as pow(radius, 2) even with java.lang.math
}
}
So the calcArea is the part being called in the second function to calculate the area of the circles. I have tried making it public float calcArea() but that brought up a whole new set of errors.
The second class:
import java.util.*;
public class Prac5
{
public Prac5() { //Not sure why, but my lecturer says it should be like this
}
public static void main(String[] args) {
int circleNum;
float radius=0;
float big=0;
Scanner scan =new Scanner(System.in);
Scanner rad =new Scanner(System.in);
System.out.print("Enter the number of circles: ");
circleNum = scan.nextInt();
for(int i=1; i<circleNum;i++)
{
Prac4 circle1 = new Prac4(); //Trying to call in the other class
System.out.printf("Enter the circle %d radius: ", i);
circle1.setRadius(radius);
System.out.printf("The radius is: %f", rad);
double area = circle1.calcArea(radius); //This is where the error occurs, the .calcArea is highlighted
if (big<area)
{
big = area;
}
}
System.out.printf("The biggest area is: %f",big);
}
}
I've declared the area as a double thinking it would work because calcArea is a double, and there was errors when I tried keeping everything as a float or double. I'm still new to java, so maybe there is something I'm missing?
Edit: The full error -
method calcArea in class Prac4 cannot be applied to given types;
required: no arguments
found: float
Reason: actual and formal argument lists differ in length
This call
double area = circle1.calcArea(radius);
doesn't match the method defined in the Prac4 class, which takes no arguments:
public double calcArea()
Change it to :
double area = circle1.calcArea();
You don't have to pass the radius to calcArea(), since you're already passing it to setRadius here - circle1.setRadius(radius); - which stores the radius in the circle1 instance.
From what I am seeing, you are calling this: double area = circle1.calcArea(radius); but you have this: public double calcArea() {, that is, your calcArea does not take any parameters. Calling it like so: double area = circle1.calcArea(); should fix the problem.
I am trying to design and implement a Java class to represent a 3-D geometric shape. The class should contain a constructor, appropriate data fields and methods to return the volume of the shape, and the surface area of the shape and any other methods that seem to make sense for your shape.
However, I got everything to work fine in Net Beans, but when I try to run it in the command prompt I receive:
error package Cube doesn't exist
error cannot find symbol
both of these error are referring to the class cube
My code is as follows.
package cube;
public class Cube {
private double side = 0.0;
public Cube(){//begin constructor
side = 1.0;
}//end constructor
public void setSide (double length) {//begin method
side = length;
}//end method
public double getSide () {//begin method
return side;
}//end method
public double calculateVolume() {
double volume2 = side * side * side;
return volume2;
} // end method
public double calculateSurfaceArea() {
double area = 6 * (side * side);
return area;
} // end method
}//end class
package randygilmanhw4;
import java.util.Scanner;
import cube.Cube;//imports class Cube
public class RandyGilmanHW4 {
public static void main(String[]args) {//begin main
//Display welcome message
System.out.println("Hello Welcome to Randy's Cube");
System.out.println(" Calculator Program");
System.out.println("");
Cube one = new Cube();
//declare variables within main
double area;
double volume2;
double side1;
Scanner input = new Scanner(System.in);
System.out.println("Please enter a length of the side of the cube in cm: ");
side1 = input.nextDouble();
one.setSide(side1);
volume2 = one.calculateVolume();
System.out.printf("Cube's volume is: %4.2f cm^3", volume2);// OUTPUT
System.out.println("\n");
one.setSide(side1);
area = one.calculateSurfaceArea();
System.out.printf("Cube's surface area is: %4.2f cm^2 ", area);// OUTPUT
} // end main
}//end class
Simple - when you save it into a .java file, remove the line "package cube;" and save. It should now work - "package" is used for your IDE, not with notepad/cmd prompt. Save your file as RandyGilmanHW4.java