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
Related
This is my code right now:
import java.util.Scanner;
import java.util.*;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
public class IceCreamData
{
// method to calculation volume
public static void printCylinderVolume(double cylinderRadius, double cylinderHeight){
double cylinderVolume = Math.PI * Math.pow(cylinderRadius, 2) * cylinderHeight;
return cylinderVolume;
}
// method to calculate number of ice cream scoops
public static double printNumScoops(double cylinderVolume){
double numScoops = (cylinderVolume * 0.004329) * 30;
System.out.println("The number of scoops is " + cylinderVolume);
}
// the main method
public static double main(String[] args) throws FileNotFoundException, IOException
{
//input the file and scanner and output file
File input = new File("project4Data.txt");
Scanner in = new Scanner(input);
PrintWriter out = new PrintWriter("scoopResults.txt");
//declaring variables outside of while-loop in order to run
String iceName; // name of the ice cream
double cylinderRadius; // cylider radius
double cylinderHeight; // cylinder height
int expirationYear; // expiration year
// while-loop to determine number of scoops in a container of ice cream
while(in.hasNext())
{
iceName = in.next(); // ice cream name
cylinderRadius = in.nextDouble(); // radius of the cylinder
cylinderHeight = in.nextDouble(); // height of the cylinder
//while-loop
while(cylinderRadius > 0 && cylinderHeight > 0 && expirationYear <= 2018){
System.out.println(iceName);
printCylinderVolume(cylinderRadius, cylinderHeight);
printNumScoops(cylinderVolume);
}
}
}
}
I am trying to return the cylinder volume from the printCylinderVolume method to the main method, so that I can use it in the printNumScoops method. Right now I am getting an error saying that cylinderVolume is an unexpected return value, and another error saying that the printNumScoops method can't find cylinderVolume. Is cylinderVolume initialized/declared in the right places and does it need to be returned/stored in the main method differently to work?
Your method should return a double, not a void:
public static double printCylinderVolume(double cylinderRadius, double cylinderHeight) {
// Here --^
double cylinderVolume = Math.PI * Math.pow(cylinderRadius, 2) * cylinderHeight;
return cylinderVolume;
}
You may want to consider renaming the method, though, since it doesn't actually print anything, it just returns the calculation. calcCylinerVolume could be a more appropriate name.
You have incorrect way in creating a method. For example, in this following method:
public static void printCylinderVolume(double cylinderRadius, double cylinderHeight){
// ^
// the method need void return
double cylinderVolume = Math.PI * Math.pow(cylinderRadius, 2) * cylinderHeight;
return cylinderVolume;
// But, you're returning double
}
You're creating a method with void return. but at the end of the method you are returning a double.
And in the following code:
// the main method
public static double main(String[] args) throws FileNotFoundException, IOException {
...
}
If you're trying to create a main method, then the above code is incorrect. main method should return a void like this:
public static void main(String[] args) {
...
}
Please read more about Defining a method in https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
I created a module that's called within another module, and it looks something like this:
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere (itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
but, I'm getting the error of "illegal start of expression" with the line where I make the method header for the second module. It looks constructed correctly.
Complete code as follows:
//This program will find the area or volume of a circle or sphere, respectively.
import javax.swing.JOptionPane;
public class Java_Chapter_9
{
public static void main(String args[])
{
//Declarations
String itemShape; //type of shape
String runProgram; //user control
Double itemRadius; //radius of tem
Double finalAnswer; //calculation for final answer
//End Declarations
showGreeting (); //Call greeting module
runProgram = JOptionPane.showInputDialog("Please enter 'Y' to run the program, or 'N' to quit"); //giving user control
while (runProgram.equalsIgnoreCase("y")) //loop for continuous use
{
itemShape = getItemShape (); //calling itemShape module
itemRadius = getItemRadius (); //calling itemradius module
finalAnswer = calculateAnswer (itemRadius, itemShape); //calling the module for calculation with paramaters
runProgram = JOptionPane.showInputDialog("Enter 'Y' to input more, or 'N' to Quit");
}
showGoodbye ();
////////////////////////////////////////////////// starting modules
public static void showGreeting () //greeting module
{
System.out.println("Welcome to the program");
System.out.println("This program will show you the area or volume of a shape");
}
///////////////////////////////////////////////// seperating modules
public static String getItemShape ()
{
String typeOfShape;
typeOfShape = JOptionPane.showInputDialog("Please enter 'C' for a Circle, or 'S' for a Sphere"); //getting input for shape
return typeOfShape; //returning to method
}
////////////////////////////////////////////////// seperating modules
public static double getItemRadius ()
{
double radiusOfItem; //variable withing scope of module
String radiusOfItemInput;
radiusOfItemInput = JOptionPane.showInputDialog("Please enter the radius of the item in inches: ");
radiusOfItem = Double.parseDouble(radiusOfItemInput);
return radiusOfItem;
}
////////////////////////////////////////////////// seperating modules
public static double calculateAnswer (double itemRadius, String itemShape);
{
double circleArea;
if (itemShape.equalsIgnoreCase("c"))
{
circleArea = 3.14159 * (itemRadius * itemRadius);
System.out.print("The area of the circle in inches is " + circleArea);
return circleArea;
}
else
{
calculateAnswerSphere(itemRadius);
}
/////////////////////////////////////////////// seperating method
public static double calculateAnswerSphere(double itemRadius);
{
double sphereVolume;
sphereVolume = (4.0/3) * 3.14159 * (itemRadius * itemRadius * itemRadius);
system.out.print("The volume of the sphere in cubic inches is " +sphereVolume);
}
end If;
}
public static void showGoodbye ()
{
System.out.println("Thank you for using the program. Goodbye.");
}
Specifically, I appear to be having problems in general calling the modules, but none of the text is overly clear and how to make a module fit within the main method, which is where I'm struggling.
There are a lot of errors in your code.
Remove the ; in function. ; is not needed for function.
public static double calculateAnswerSphere(double itemRadius); // remove ;
After showGoodBye() method is being called, you miss to add a close brackets.
You have a typo in this line
system.out.print
It should be System.out.print and so on...
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.
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'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.