Invoking static methods from another class - java

So I've spent the last couple days working on this program, and I've hit a roadblock. I am trying to make a calculator that uses specific programs with user input to calculate the Surface area or Volume of multiple shapes. You might recognize this as project 8.5 from the Horstmann java concepts book.
I don't know how to call the methods from one file to another, and need to figure it out.
Here's the code:
import java.util.Scanner;
public class p85SantoCharlie{
public static double sphereVolume(double r){
Scanner in = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
double volume = (4/3) * Math.PI * r * r * r;
System.out.println(volume);
return volume;
}
public static double sphereSurface(double r){
Scanner in = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
double surface = 4 * Math.PI * r * r ;
System.out.println(surface);
return surface;
}
public static double cyliderVolume(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double volume = Math.PI * r * r * h ;
System.out.println(volume);
return volume;
}
public static double cylinderSurface(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double surface = 2 * Math.PI * r * r * h ;
System.out.println(surface);
return surface;
}
public static double coneVolume(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double volume = Math.PI * r * r * h / 3 ;
System.out.println(volume);
return volume;
}
public static double coneSurface(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double surface = Math.PI * r * (r + Math.pow(( r * r + h * h), .5));
System.out.println(surface);
return surface;
}
}
And here is the main file:
import java.util.Scanner;
public class p85SantoCharlieMain{
public static void main(String[] args){
p85SantoCharlie mainProgram = new p85SantoCharlie();
Scanner in = new Scanner(System.in);
System.out.println("Please select a shape");
System.out.println("your choices are: Sphere, Cylinder, and Cone");
String answer1 = in.next();
String answer1Caps = answer1.toUpperCase();
System.out.println("Fantastic! now select a formula");
System.out.println("your choices are: surface area or volume");
String answer2 = in.next();
String answer2Caps = answer2.toUpperCase();
if (answer1Caps.equals("SPHERE")&& answer2Caps.equals("SURFACE AREA")){
mainProgram.sphereSurface();
}
}
}
Thanks!

If the methods are static you can call them using the class name
p85SantoCharlie.sphereVolume(1.1);
And if they aren't static initialize new class instance and use it to call
p85SantoCharlie p = new p85SantoCharlie();
p.sphereVolume(1.1);

Three problems:
First, all of your calculation methods in p85SantoCharlie are static. You don't need an instance of p85SantoCharlie to invoke them. You should get rid of the line where you do new p85SantoCharlie() and invoke your methods like
p85SantoCharlie.sphereVolume(r);
Second, you have declared your calculation methods as taking parameters, but you don't know those parameters when you invoke them. For example, sphereVolume() is declared as taking double r. But you don't know the value of r until you read it in within the sphereVolume() method. So that can't work. You need to change your main method to ask for the radius, then pass it to sphereVolume as shown above.
Third, all of those Scanners! Get rid of them all except for the one in main. You will be passing in the value of r (or whatever) when you invoke the calculation method. Just use what is passed in.

Ugly, unreadable code.
Java's an object-oriented language. I would expect that you'd start with a Shape interface:
public interface Shape {
double surfaceArea();
double volume();
}
I'd expect to see subclasses for different types that would do the calculation appropriately. Here's a Sphere implementation:
public class Sphere implements Shape {
private final double radius;
public Sphere(double radius) {
if (radius <= 0.0) throw new IllegalArgumentException("radius must be positive");
this.radius = radius;
}
public double surfaceArea() {
return 4.0*Math.PI*this.radius*this.radius;
}
public double volume() {
return 4.0*Math.PI*this.radius*this.radius*this.radius/3.0;
}
}
Here's a Cylinder implementation:
public class Cylinder implements Shape {
private final double radius;
private final double height;
public Cylinder(double radius, double height) {
if (radius <= 0.0) throw new IllegalArgumentException("radius must be positive");
if (height <= 0.0) throw new IllegalArgumentException("height must be positive");
this.radius = radius;
this.height = height;
}
public double surfaceArea() {
return 2.0*Math.PI*this.radius*this.radius + this.radius*this.height;
}
public double volume() {
return Math.PI*this.radius*this.radius*this.height;
}
}
I'd expect to see your driver class interact with Shape objects to solve the problem.
You'll want to consider a virtual constructor/factory for Shape, because you won't want to clutter your code with if/else constructs.
My opinion: Object-oriented programming was invented to solve two problems:
Encapsulation of state and behavior into a single abstract data type.
Inheritance and polymorphism to eliminate if/else and switch statements.
Do not clutter your code with "if sphere and area" kinds of decisions. Let polymorphism handle it for you.
New programmers tend to spend too much time worrying about user interfaces. Concentrate on the functionality and get that working first. Don't create a bunch of text question/answer code and leave the meat of the problem undone.

Related

Problems with scanning in java

I got a task, where I have to calculate the perimeter and area of a given object, that's determined by the user, with accompanying data - side length, radius, etc. To do this I have to do a "GUI" as my teacher said, and to do that, I have to use the Scanner.
Everytime I try to do the second scan, after the user has choosen what object we are dealing with, when it gets to the part, where the user's supposed to input their data about their object, it always crashes, with a java.util.NoSuchElementException error, according to NetBeans. I looked through it, and even copied in the working scanner, but to no avail.
Here's the full code:
package Methods2;
import java.util.Scanner;
public class Methods2 {
public static void main(String[] args) {
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
input1.close();
//decision
if (decider == 1) {
circle();
} else if (decider == 2) {
square();
} else if (decider == 3) {
rectangle();
} else {
System.out.println("There aren't any other options, other than these three.");
}
}
public static void circle() {
//method specific initialization
int radius;
double pi;
double perimeter;
double area;
Scanner input2;
//define
pi = 3.14;
input2 = new Scanner(System.in);
System.out.println("Please type in the radius of the circle!");
radius = input2.nextInt(); //these are where my problem's lie
input2.close();
//calculate
perimeter = 2 * radius * pi;
area = radius * radius * pi;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void square() {
//method specific initialization
int a;
int perimeter;
int area;
Scanner input3;
//define
input3 = new Scanner(System.in);
System.out.println("Please type in one side's length of the square!");
a = input3.nextInt(); //these are where my problem's lie
input3.close();
//calculate
perimeter = 4 * a;
area = a * a;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
public static void rectangle() {
//method specific initialization
int a;
int b;
int perimeter;
int area;
Scanner input4;
//define
input4 = new Scanner(System.in);
System.out.println("Please type in one of the sides' length of the rectangle!");
a = input4.nextInt(); //these are where my problem's lie
System.out.println("Now type the other, non-equal side, compared to the previous one!");
b = input4.nextInt(); //these are where my problem's lie
input4.close();
//calculate
perimeter = 2 * (a + b);
area = a * b;
//print
System.out.println("The perimeter of this circle is: " + perimeter);
System.out.println("The area of this circle is: " + area);
}
}
I have thought about it being multiple Scanner's, but after I realized, that variables don't carry over between methods, unless they're defined within the class, that was swiftly thrown out as a theory. Also, NetBeans didn't mark any problems with that line, so it made even less sense to me.
The reason why your code is "stopping" the scanner, is because you added input1.close();. What .close() does, is that it closes the scanner. Once a scanner is closed, you won't be able to open it again. According to your code, you use the Scanner.. even after it was closed. So to fix your problem, removed the line:
input1.close();
Here is a close up of where you should remove the line:
//initialization
int decider;
Scanner input1;
//defining
input1 = new Scanner(System.in);
System.out.println("Choose from these options to find the perimeter and area of any of these:\n1. Circle\n2. Square\n3. Rectangle");
decider = input1.nextInt();
//input1.close(); REMOVE THIS LINE

Is there any way I can rewrite my methods better?

I'm not entirely sure if there is an easier answer to this question and I'm thinking to hard about it or what, but I'm currently programming a rectangular block program to practice Java. It's structured to have 4 methods: getInput, volBlock, saBlock, and display, and I want to use only local variables for these methods. Is there a way that I can utilize getInput to accept and return a single double from the user and if so, how can I use that input in my other methods?
I constructed this code, which uses local variables in getInput() and then passes those values to other methods, but I couldn't figure out a display method so I hard coded it into the calculation methods themselves.
Here is that code:
import java.util.*;
public class Block {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String choice = "Y";
while (choice.equals("Y")){
getInput();
System.out.println("Would you like to do another calculation?(Y/N): ");
choice = in.next().toUpperCase();
}
System.out.println("Program now ending...");
}
public static void getInput() {
double l, w, h;
Scanner fin = new Scanner(System.in);
System.out.println("Please enter the length, width, and height in that order: ");
l = fin.nextDouble();
w = fin.nextDouble();
h = fin.nextDouble();
volBlock(l, w, h);
surfaceAreaBlock(l,w,h);
}
public static void volBlock(double length, double width, double height) {
double volume;
volume = length * width * height;
System.out.println("The volume is: " + volume);
}
public static void surfaceAreaBlock (double l, double w, double h) {
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
System.out.println("The surface area is: " + surfaceArea);
}
}
I'm sorry if this question is kind of scrambled, I am having a hard time figuring all of this out. I'm quite new to Java.
Any help is appreciated, thank you!
If you're practicing java, you should probably familiarize yourself more with object oriented programming before you go any further, because your code leads me to believe that you're more used to procedural languages (e.g. C, C++, etc). Java doesn't rely on having several static helper methods in its main; the preferred approach is to construct a few classes that perform these calculations for you, and you use the results created by these functions for your basic input/output, which is normally what main is used for.
I implemented a block class to demonstrate what I mean:
public class Block {
private double length;
private double width;
private double height;
public Block(double l, double w, double h) {
length = l;
width = w;
height = h;
}
public double getVolume() {
return length * width * height;
}
public double getSurfaceArea() {
return 2 * length * (height + width) + height * width;
}
/* This is the "display" method that you want */
public String toString() {
return "The volume is: " + getVolume() + "\n"
"The surface area is: " + getSurfaceArea();
}
}
using the Block class, your main becomes much more simple:
public static void main() {
Scanner in = new Scanner(System.in);
char choice = 'y';
do {
System.out.print("Please enter the dimensions of the block: ");
double length = in.nextDouble();
double width = in.nextDouble();
double height = in.nextDouble();
Block block = new Block(length, width, height);
System.out.println(block);
System.out.print("continue (y/n)? ");
choice = in.nextLine.toLowerCase().charAt(0);
} while (choice == 'y');
}
If you return the values from your getInput(), volBlock() and surfaceAreaBlock() methods you might be able to structure the rest as you want to.
For instance surfaceAreaBlock becomes:
public static double surfaceAreaBlock (double l, double w, double h){
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
return surfaceArea;
}
and then when you call surfaceAreaBlock you can do this:
public static void main(String[] args) {
...
double surfaceArea = surfaceAreaBlock();
// Do something with the surface area in this method
...
}

How to print a static method in java that takes an int as parameter and returns a double

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

Function method, finding volume of a sphere

public class Part1
{
public static void main(String args [])
{
DecimalFormat df=new DecimalFormat("###.##");
double v;
Scanner sc = new Scanner( System.in );
double radius;
System.out.println( "Enter radius of the basketball: " );
radius = sc.nextDouble();
System.out.println("The volume of the basketball is " +df.format(v));
}
public static int volume (int v)
{
v= ( 4.0 / 3.0 ) * Math.PI * Math.pow( radius, 3 );
}
}
Basically, i have to let the user input the radius of the basketball and you have to calculate the volume of the basketball. the codes works perfectly, but i don't know how to do it in function method?
I'm fairly certain you need to return double and pass the radius as a double to your volume method. You also need to call the function and get the value. You should try and restrict the lexical scope of your variables. Something like,
public static void main(String args[]) {
DecimalFormat df = new DecimalFormat("###.##");
Scanner sc = new Scanner(System.in);
System.out.println("Enter radius of the basketball: ");
double radius = sc.nextDouble();
double v = volume(radius);
System.out.println("The volume of the basketball is " + df.format(v));
}
public static double volume(double radius) {
return (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);
}

Why doesn't my code show presentValue?

package presentvalue;
import java.util.Scanner;
public class PresentValue {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double P; // present value
double F; // future value
double r; // annual interest rate
double n; // number of years
P = presentValue();
F = futureValue();
r = annualInterest();
n = years();
System.exit(0);
}
public static double presentValue()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the presnt value of you savings account?");
return keyboard.nextDouble();
}
public static double futureValue()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("How much do you want in your account in the future?");
return keyboard.nextDouble();
}
public static double annualInterest()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("What is youe bank's interest rate?");
return keyboard.nextDouble();
}
public static double years()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many years will the money in the bank?");
return keyboard.nextDouble();
}
public static double presentValue(double F, double r)
{
return F/(1+(r * r));
}
public static void show(double presentValue)
{
System.out.println(presentValue);
}
}
The question says write a method presentValue that preforms this calculation. The method should accept the future value, annual interest rate, and number of years as arguments. It should return the present value, which is the amount that you need to deposit today. Demonstrate the method in a program that lets the user experiment with different values for the formula's terms.
Here is the formula P = F/(1+r)^2
You will have to use Math.pow:
public static double presentValue(double future, double intrest, double years)
{
return future / Math.pow(1.0 + intrest, years);
}
Note that I added the amount of years. You stated two years, but I think you really want to have a parameter to specify the number of years, because, otherwise you wouldn't ask the user for an amount of years, right?

Categories