How to call a method within a method - java

While this may be incredible simple, I am having trouble with it.
I had to create a Fahrenheit to Celsius, and Celsius to Fahrenheit converter. The assignment after this one is to:
In the main method declare a variable of type double
and initialize it to a value. 3. Add a line in the main that calls the fToC method and passes as its argument the variable declared in step 2.
I know that too declare a variable and set it to a number, I will have to do this:
double var = 0;
But I do not know how to call in the method in this.
I tried calling the method, but it seems to be improper format, and I can not find how to properly do it (Googled quite a bit :( )
import java.util.Scanner;
public class ExerciseOne {
public static void main( String[] args ) {
int choice;
double variable = 0;
public static float ftoC(double var) { //This line is giving me trouble
System.out.println( "What would you like to do? \n \n 1 - Fahnrenheit to Celsius \n 2 - Celsius to Fahrenheit \n 3 - Quit" );
Scanner dylan = new Scanner(System.in);
choice = dylan.nextInt();
if (choice == 1)
{
System.out.println( "What number do you want to convert to Celsius?" );
float input = dylan.nextFloat();
float output = ftoC(input);
System.out.println( input + " degrees Fahrenheit is " +
ftoC(input) + " degrees Celsius." );
}
if (choice == 2)
{
System.out.println( "What number do you want to convert to Fahrenheit?" );
float input = dylan.nextFloat();
float output = ctoF(input);
System.out.println( input + " degrees Celsius is " +
ctoF(input) + " degrees Fahrenheit." );
}
if (choice == 3)
{
System.out.println( "Exiting application.");
}
}
}
public static float ftoC(float f)
{
float celsius = (f-32)*(5f/9f);
return celsius;
}
public static float ctoF(float c)
{
float fahrenheit = c*9/5 + 32;
return fahrenheit;
}
}

To call the ftoC method, you use the following syntax:
ftoC(x); // Assuming x is the name of the float you created.
NOTE: One thing I noticed in your example, is you're declaring the value to pass in as double variable = 0;, but your method is expecting a float. If you pass double to a method expecting a float, then it will not compile. You need to change double variable into float variable.
NOTE NOTE: One more thing. You should name your variables appropriately. Even calling it value is better than calling it variable. The name variable tells the reader nothing about the purpose of it.
NOTE x 3: Another thing I noticed, is you're setting your variable to a value of 0, yet the question specifies:
In the main method declare a variable of type double and initialize it to a value. 3.
So you should think about replacing that 0 with something glaringly obvious.

to perform:
In the main method declare a variable of type double and initialize it
to a value. 3. Add a line in the main that calls the fToC method and
passes as its argument the variable declared in step 2.
you just have to call the method and assign the result to the variable like you already did in the rest of the main method (for options 1 and 2). Here is how you need to modify the first part of the main method:
import java.util.Scanner;
public class ExerciseOne
{
public static void main( String[] args )
{
int choice;
float initialF = 3; // assign variable to 3 initially
float resultC = ftoC(variable); // simply call the method and assign the result to a variable
…then the rest of the main method as you have it.

Your code is a little confused. You've defined ftoC() twice, once within main() and once as its own function. Then your main() function does nothing but included the embedded ftoC() function. Nothing actually ever gets called.
The solution is to remove the inner ftoC().
Note: you could have defined ftoC() and ctoF() within the body of main(), but there's nothing to be gained, really, and nobody does it that way.
import java.util.Scanner;
public class ExerciseOne {
public static void main( String[] args ) {
int choice;
double variable = 0;
System.out.println( "What would you like to do?\n\n" );
System.out.println( " 1 - Fahnrenheit to Celsius\n" );
System.out.println( " 2 - Celsius to Fahrenheit\n" );
System.out.println( " 3 - Quit]n" );
Scanner dylan = new Scanner(System.in);
choice = dylan.nextInt();
if (choice == 1)
{
System.out.println( "What number do you want to convert to Celsius?" );
float input = dylan.nextFloat();
float output = ftoC(input);
System.out.println( input + " degrees Fahrenheit is " +
ftoC(input) + " degrees Celsius." );
}
if (choice == 2)
{
System.out.println( "What number do you want to convert to Fahrenheit?" );
float input = dylan.nextFloat();
float output = ctoF(input);
System.out.println( input + " degrees Celsius is " +
ctoF(input) + " degrees Fahrenheit." );
}
if (choice == 3)
{
System.out.println( "Exiting application.");
}
}
public static float ftoC(float f) { /* same as before */ }
public static float ctoF(float f) { /* same as before */ }
}
There were other things that could be fixed, but they're beyond the scope of this question.

Related

how can I take one methods result as another methods' parameter

I need to take this "over" statement under the overallmethod as finalmethods' parameter, how can I do this. I want to learn the final letter but to do that I want to access over statement.
public static void overallmethod(int quiz1,int quiz2,int quiz3,int midterm,int grade){
double quizzes = ( ((quiz1*10) + (quiz2*10) + (quiz3*10)) *25) /300;
double finalg = ( grade * 40) / 100;
double mid = (midterm * 35) / 100;
double over = quizzes + finalg + mid;
System.out.println("Your overall score is: " + over);
}
public static void finalmethod(double over){
if(over <= 100 && over >= 90){
System.out.println("Your final letter is: A");
}
else if(over >= 80) {
System.out.println("Your final letter is: B");
}
else if (over >= 70) {
System.out.println("Your final letter is: C");
}
else if (over >= 60) {
System.out.println("Your final letter is: D");
}
else{
System.out.println("Your final letter is: F");
}
}
You're going to need to return the variable over and change your return type to double.
public static double overallmethod(int quiz1,int quiz2,int quiz3,int midterm,int grade)
{
//Your code
return over;
}
Then simply pass the value returned from the overallmethod to finalmethod.
over is not a statement, it is a local variable now. Just make it class attribute:
public static double over
Make your overall function return the value of over. Then just call the overall function inside the parameter list of finalmethod
The best solution would be to declare over as a private int outside both the methods, i.e. it should have visibility to all the methods in that class (class variable).
Now compute the overall score in the overallMethod and store it to the over variable.
Next, make a public method getOver() which returns the value of over, and call finalMethod in this way : ClassName.finalMethod(objectOfClass.getOver())
By changing the return type of your method to double, and then passing the value in that method to the final method.

The method ____ is undefined for the type ____

Okay so I have a homework assignment and I'm having difficulty calling a method on my main class that is in another class.
Basically the "test" method is in the landEnclosure.java class and I'm trying to call it on my main class which is landAndEat.java
They're both inside the same package:
Image
This is the main class where I'm trying to call the method:
public class landAndEat {
public static void main(String[] args) {
test();
} //end class
} //end main
This is the class where the method is being created:
import java.util.Scanner;
public class landEnclosure {
public void test() {
double area, ratioA = 0, ratioB = 0, x, l, w, perimeter;
Scanner input = new Scanner(System.in);
System.out.println("What area do you need for your enclosure in square feet?");
area = input.nextDouble();
if( area > 0 && area <= 1000000000) { //Input specification 1
System.out.println("What is the ratio of the length to the width of your enclosure?");
ratioA = input.nextDouble();
ratioB = input.nextDouble();
}
else
System.out.println("It needs to be a positive number less than or equal to 1,000,000,000!");
if(ratioA > 0 && ratioA < 100 && ratioB > 0 && ratioB < 100) { //Input specification 2
x = Math.sqrt(area/(ratioA*ratioB));
l = ratioA * x;
w = ratioB * x;
perimeter = (2 * l) + (2* w);
System.out.println("Your enclosure has dimensions");
System.out.printf("%.2f feet by %.2f feet.\n", l, w);
System.out.println("You will need " + perimeter + " feet of fence total");
}
else
System.out.println("The ratio needs to be a positive number!");
}
} //end class
In java the only top level "things" are classes (and similar stuff such as interfaces and enums). Functions are not top level "things". They can exist only inside a class. Thus to call it you need to go through that class, or through an object of that class.
From the code you have written it seems that test is a non static method. In that case you need to create an object from that class, and run the method on it :
landEnclosure l = new landEnclosure();
l.test();
However, it seems that your intention is for 'test' to be a static method. In that case, declare it static and call it that way :
landEnclosure.test();
On a side note, the convention in Java is to name classes with an upper case first :
class LandEnclosure {
Besides the obvious suggestions of creating a new instance of landEnclosure, you can also make the function static and call:
landEnclosure.test();

Calling a method adding input

I'm having problems finding out how to get the output based on the user inputs for my Main class. I already have keyboard entry where the users can enter a value, which will be held. I'm guessing I will need to use that e.g. (input.input1());. However I also need to include the method which calculates the result e.g calculations.theAverageMassFfTheVehicle from the CalculatingRocketFlightProfile class, I'm just not sure how to combine the two to get the result.
//Calculations class
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass;
//Declaring variables for outputs
public double theAverageMassOfTheVehicle;
public double theVehiclesMaximumVelocity;
public CalculatingRocketFlightProfile(double totalImpulse, double averageImpulse, double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) { //Constructor for this class
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Mutators and Accessors
//Accessors
//Methods for calculations - Calculating outputs, using inputs.
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}//method
public double theVehiclesMaximumVelocity() { //Formula to calculate Maximum velocity
return totalImpulse / getTheAverageMassOfTheVehicle();
}//method
//Returns - GET
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}//method
public double getTheVehiclesMaximumVelocity() {
return theVehiclesMaximumVelocity;
}//method
}//class
//Main class
public class Main { //Master class
public static void main( String args[] ) //Standard header for main method
{
kbentry input = new kbentry();
System.out.print("\nPlease enter a number for Total Impulse: " );
System.out.println("You have entered : " +input.input1());
System.out.print("\nPlease enter a number for Average Impulse: " );
System.out.println("You have entered : " +input.input2());
System.out.print("\nPlease enter a number for Time ejection charge fires: " );
System.out.println("You have entered : " +input.input3());
System.out.print("\nPlease enter a number for the Mass of the vehicle: " );
System.out.println("You have entered : " +input.input4());
System.out.print("\nPlease enter a number for the Mass of the engine: " );
System.out.println("You have entered : " +input.input5());
System.out.print("\nPlease enter a number for the Mass of the fuel: " );
System.out.println("You have entered : " +input.input6());
//Output
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() +
"\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity());
}
}
//kbentry
public class kbentry{
double input1(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Total Impulse entry
String strTotalImpulse = null; // These must be initialised
int intTotalImpulse = 0;
//System.out.print("Please enter a number for Total Impulse: ");
//System.out.flush();
// read string value from keyboard
try {
strTotalImpulse = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intTotalImpulse = Integer.parseInt(strTotalImpulse);
}
catch (NumberFormatException nfe) {
System.out.println("Error! Please enter a number!" + nfe.toString());
}
The problem is that you're CalcultingRocketFlightProfile class needs parameters, but you're creating calculations without passing any parameters to the new CalcultingRocketFlightProfile.
You should store those inputs in variables, then pass those variables to the constructor in your new CalcultingRocketFlightProfile that you declare.
Well, first off you are not actually passing any of your input to the Calculations class. I am not sure what input.input1() is or if you have an input class that you did not post. Either way you can do this a couple different ways.
First off give your input variables a meaningful name so you know which ones you are dealing with. Then pass all of your input.
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(input1, input2, etc..)
or
Place all your input variables into your calculations class. Then store user input as calculations.totalImpulse, etc... Then you call your calculation methods to display answers.
-EDIT-
Just have 2 classes, your main and calculations class. There is no need for another class just to handle keyboard input.
Example
Main class
public class Main {
public static void main( String args[] ) {
Scanner keyboard = new Scanner(System.in);
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.print("\nPlease enter a number for Total Impulse: " );
calculations.totalImpulse = keyboard.nextDouble();
System.out.println("You have entered : " + calculations.totalImpulse);
}
}
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
// Do all of your maths, and methods for answer return
}
You were not actually taking the keyboard input and assigning it to anything. Using a scanner object you can assign the input to a variable in your calculations class. If you do that for all of them, you dont actually need a constructor in your calculations class, you just use it to do all that math and return answers.

Passing Variables between methods?

So im trying to write a simple java program for college and I'm a complete newbie at this java stuff. I keep getting an error when I compile, "error - could not find symbol" within the method printreciept. I know that it's something like not being able to access the variables within the main. Could anyone help? I know I'll prob have alot of errors if I do fix it but I'd rather start here! P.S. sorry for all of the code :/
import java.util.Scanner;
public class Order {
public static void main (String[] args) {
String clubcard;
double clubcard_discount;
double special_discount;
double balance;
double final_balance;
int apples;
int oranges;
int apples_cost;
int oranges_cost;
final Scanner scanner = new Scanner( System.in);
System.out.println("How Many Bags of Apples?");
apples = scanner.nextInt( );
System.out.println("How many bags of Oranges?");
oranges = scanner.nextInt( );
System.out.println("Do you have a clubcard? Yes/No");
clubcard = scanner.nextLine();
if(clubcard == "Yes") {
clubcard_discount = clubcard_discount - 1.0;
final_balance = final_balance - (balance / 100 * 10);
}
else if(clubcard == "No") {
special_discount = 0.0;
}
if(apples == 3) {
special_discount = -1.0;
balance = balance - 1.0;
}
}
//Calculating the cost of apples and oranges
public void calculate_apples (final double apples_cost ) {
apples_cost = apples * 1.0;
}
public void calculate_oranges (final double oranges_cost ) {
oranges_cost = oranges * 1.25;
}
//Printing the receipt
public static void printReceipt() {
System.out.println("Bags of apples: " + apples);
System.out.println("Bags of oranges: " + oranges);
System.out.println("Clubcard: " + clubcard);
System.out.println( );
System.out.println("Price for apples: " + apples_cost);
System.out.println("Special discount: " + special_discount);
System.out.println("Price of oranges: " + oranges_cost);
System.out.println("Total: " + balance);
System.out.println("Clubcard discount: " + clubcard_discount);
System.out.println( );
System.out.println("Final price: " + final_balance);
System.out.println( );
System.out.println("Thanks for doing business with CS2500.");
}
}
You have declared all your variables as local variables inside the main method, so they aren't in scope outside main. To have them accessible to other methods, you can do one of the following:
pass them to the methods as parameters
declare them as static class variables outside any methods, but inside the class.
You can add the variables making them static .
public class Order {
static String clubcard;
static double clubcard_discount;
static double special_discount;
static double balance;
static double final_balance;
static int apples;
static int oranges;
static int apples_cost;
static int oranges_cost;
public static void main (String[] args) { ...
Try this and let us know.
You aren't passing the variables, that's the problem. You declared them in main. However, if you declare them as static variables before the main method, that will work.
variables declared inside any method are for that method only(local scope).
Either declare those methods at class level or pass them as arguments from main(as per use case, if methods being called from main).
The variables you are passing are visible only inside main.
The function printReceipt() is unable to see the variables because they are out of its scope of visibility.
Here you have few options you can try and the program will work:
Declare the variables as the data members of the public class Order rather than keeping them as members of the main() function (best option).
public class Order{
static String clubcard;
static double clubcard_discount;
static double special_discount;
static double balance;
static double final_balance;
static int apples;
static int oranges;
static int apples_cost;
static int oranges_cost;
//main() and other functions...
}
OR
Pass the data members as arguments to the PrintReceipt() function (though this may make you function a bit messy).
public static void printReceipt(int apples, int oranges, .... .... ){
//...defining your function
}
Hope this helps!

How to call up calculations in custom methods to main Method

I have a main method and 4 other function type methods which include calculations, however, How would I call each one up into the main and proceed to print out the calculations. Also I am currently getting a lot of syntax errors.
I've tried placing brackets and braces when needed, however, that has just resulted into more errors. Also, I tried initializing Strings and integers elsewhere, which still seems to fail to work. Any help would be much appreciated!
Some syntax errors include: ';' expected on line 60
insert ';' to complete localVariableDelcartion on line 60
these errors are repeated for every line
import java.io.*;
//create the class
public class CirclemethodsFixedagain
{
//main method
public static void main(String[] args) throws IOException
{
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
String numInput;
String reqInput;
String amountStr;
double numInt = 0;
double num = 0;
System.out.println("This program will ask for a given user radius, then proceed to calculate the user input");
System.out.println("The program will use four methods to achieve this, all calling back to the main method");
System.out.println("Press any key to continue");
numInput = myInput.readLine();
// more user questions
System.out.println("First, what would you like to calculate?");
System.out.println("Enter '1' for Circumference, '2' for area, '3' for volume, or '4' for surface area");
System.out.println("*NOTE* Pressing a key outside of this range or a regular character will re-prompt the original message");
reqInput = myInput.readLine();
numInt = Double.parseDouble(reqInput);
// more user questions
System.out.println("Now enter the radius of the required shape(Half of diameter)");
System.out.println("*NOTE* Pressing a regular character will re-prompt the original message");
numInput = myInput.readLine();
num = Double.parseDouble(numInput);
}
//user created method, with each
public static int circlemethods(double circumference) throws IOException {
{
if (numInt == 1)
{
System.out.println("You chose to calculate circumference, given the radius :" + num);
circumference = (Math.PI) * (2) * (num);
System.out.print("The circumference of that sphere is :");
return circumference;
}
public static double circlemethods2 (double area) throws IOException
{
if (numInt == 2)
{
System.out.println("You chose to calculate area, given the radius :" + num);
area = (Math.PI * num * num);
System.out.print("The area of the circle is :");
return area;
}
}
public static double circlemethods3 (double volume) throws IOException
{
if (numInput == 3)
{
System.out.println("You chose to calculate volume, given the radius :" + num);
volume = (4 * Math.PI * num * num * num) / 3 ;
System.out.print("The volume of that sphere is : cm³");
return volume;
}
}
public static double circlemethods4 (double surfaceArea) throws IOException
if (numInput == 4)
{
System.out.println("You chose to calculate surface area, given the radius :" + num);
surfaceArea = 4 * Math.PI * num * num;
System.out.print("The Surface area of that sphere is :");
return surfaceArea;
}
}
}
}
Your braces - the { and } characters - don't match up. I have fixed the indentation of the code in the question so that you can better see where the problem gets started - in the method circlemethods. Also, circlemethods4 is missing its braces.
Keeping consistent indentation levels throughout the program makes these kinds of errors a lot more obvious to spot.
Compilation errors are caused by:
You can not place methods inside other method, move circlemethods 2,3,4 outside the circlemethod1.
Your circlemethods don't see numInt local variable. It is declared in main method and it is visible only in that one.
I believe you don't need if statements at the begining of each circlemethods. You rather need something like that:
if (numInt == 1)
{
circlemethod1(radius);
} else if (numInt == 2) {
circlemethod2(radius);
}
etc. in your main method.
You can also change argument's name of each circlemethod, as I understood it is always radius. Current name of arguments is a good candidate for method name.
Following are the inputs that will fix the problem :
You can't declare method inside a method, It's not JAVA syntax. Just check the bracing correctly. Use any IDE for doing the same.
Make numInt, num as static (Class) variables. As you are using those in static method.
Use proper names and camelCasing nomenclature to name any method.
|e.g calculateCircleArea(), calculateCircleVolume(), etc..
Hope this solves your problem.

Categories

Resources