Passing Variables between methods? - java

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!

Related

How do i get the value of a method to use in main

i'm still pretty new with Java and am trying to write a program that will show me how much my money is actually getting me whenever i make an ingame purchase.
I'm struggling with getting the value from the method convertYourself() into my main method so that i can combine them.
I think i would most likely need make it a double instead of a void and return it but what would i pass as the parameter?
Thank you!
public class TestCode {
Scanner in = new Scanner(System.in);
public static double gemValue = 0.01;
public static double goldValue = 0.000004;
public static void main(String[] args) {
TestCode test = new TestCode();
test.convertYourself(gemValue);
test.convertYourself(goldValue);
// double sum = how do i get the value of the convertYourself method so i can use it here?
System.out.println("The total value of this bundle is :" + sum);
}
public void convertYourself(double x) {
System.out.println("How many are you buying?");
double currency = in.nextDouble();
double convert = currency * x;
System.out.println("The true value of this is: " + convert);
}
}
You would need to have the method to return a value. That can be done like this:
public double convertYourself(double x) {
System.out.println("How many are you buying?");
double currency = in.nextDouble();
double convert = currency * x;
return convert;
}
//To call it:
double valueReturned = convertYourself(gemValue);
So, you would have to change the method return value from void to double, and use the return keyword to return the value you want.
You can use a return type instead of void for a method.
The return value must then be returned via return {value}.
// return type
// \/
public double convertYourself (double x) {
double convert = /* convert */;
return convert;
}
After that you can store the output in a variable:
double result = convertYourself (/* x */);
To be more specific with the coding part:
public class TestCode {
Scanner in = new Scanner(System.in);
public static double gemValue = 0.01;
public static double goldValue = 0.000004;
public static void main(String[] args) {
// TestCode test = new TestCode(); ... you do not need this as the both methods are inside the same class. Make the convertYourself method as *static*.
double gemValueConverted = convertYourself(gemValue); // call it without the object
double goldValueConverted = convertYourself(goldValue);
double sum = gemValueConverted + goldValueConverted;
System.out.println("The total value of this bundle is :" + sum);
}
public static double convertYourself(double x) { // made the method static and added return type as double
System.out.println("How many are you buying?");
double currency = in.nextDouble();
double convert = currency * x;
System.out.println("The true value of this is: " + convert);
return convert;
}
}

Variable is reset after loop

I'm learning Java and have written a program with a for loop in it. But my variable is 0 after I print it out. Why does it get reset? This is my code:
Private static int number;
public static void main(String[] args)
{
int number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print();
}
public static void print()
{
System.out.println("Print: " + number);
}
This is the result:
run:
Main: 10
Print: 0
BUILD SUCCESSFUL (total time: 0 seconds)
Your variable is not reset. This might be hard to grasp when you're new but by saying int number; you create a new variable number of type int. Also keep in mind that variables will remain in the scope where they were created and can't be used outside that scope. This means that if you initialize a variable in a while loop, it will only be available from within that while loop. The same applies to methods.
You created a variable number on the first line, this variable can be used by every method in your class and is set to zero by default. However, you created another variable number in your main method. This second variable only exists within your main method because that's the scope where it was created in.
Let me give you some ways to fix this:
Private static int number;
public static void main(String[] args)
{
//By removing `int`, we reference the variable that has already been initialized
//instead of creating a new one
number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print();
}
public static void print()
{
System.out.println("Print: " + number);
}
This is a possibility if your variable doesn't have to be accessed any further:
public static void main(String[] args)
{
int number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print(number);
}
//We use the created variable as a parameter
public static void print(int number)
{
System.out.println("Print: " + number);
}
You have two declarations of number, one as a private static class variable, and one as an local variable in main. The local variable in main is hiding the other variable, so the static variable isn't being updated at all.
You have two variables with the same name. One is a local variable which is updated in the main loop:
public static void main(String[] args)
{
int number = 0;
//...
}
The other is a static variable which is initialised to zero:
Private static int number;
(by the way, Private should be lowercase)
Your print method is using the static variable (which never changes). You can fix this by passing a parameter to the print function:
public static void print(int number)
{
System.out.println("Print: " + number);
}
and call that from your main method like so:
print(number);
You should also remove the static variable. It's unnecessary.
you re-declared int number inside main() method. It is like to create new variable.
Just delete 'int' and it should work.
Private static int number;
public static void main(String[] args)
{
number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print();
}
public static void print()
{
System.out.println("Print: " + number);
}
You have 2 different variables named number.
One is Private static int number and another one is inside the main function int number = 0.
I believe you wanted the static member to be changed inside your loop, thus you have to remove the declaration from the main function.
Private static int number;
public static void main(String[] args)
{
number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print();
}
public static void print()
{
System.out.println("Print: " + number);
}
Your issue is to do with the scope of your variables. If you want to keep a static 'number' variable then don't include 'int' when you initialize it in the 'main' method. (see code below)
private static int number;
public static void main(String[] args)
{
number = 0; //you are now initialising the global static variable and not a local variable to the main method.
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print();
}
public static void print()
{
System.out.println("Print: " + number);
}
OR
Personally, I prefer to avoid using global variables. you can pass 'number' in as a parameter to the 'print' method instead.
public static void main(String[] args)
{
int number = 0;
for (int i = 0; i < 10; i = i + 1)
{
number = number + 1;
}
System.out.println("Main: " + number);
print(number);
}
public static void print(int number)
{
System.out.println("Print: " + number);
}

(Beginner Java): Constructor no arguments?

I am trying to make a simple program that takes the average of three number, but I get an error saying that says
"constructor average in class average cannot be applied to given types;
required: no arguments
found: int,int,int "
Here is my code:
public class ave {
public static void main(String args[]) {
average object = new average(3,4,6);
}
}
and here is my constructor code
public class average {
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave; }
}
The constructor's name should be same as the class name and feature no return type.
Try the following:
public class ave {
public static void main(String args[]) {
Average object = new Average(3,4,6);
}
}
public class Average {
public Average(double first, double second, double third){
double ave = (first + second + third)/3;
System.out.println(ave);
}
}
and if you don't want to change the code of Class Average, then just call the method from that class as following:
public class ave {
public static void main(String args[]) {
Average object = new Average();
double Avg = object.takeaverage(3,4,6);
}
}
public class Average {
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave; }
}
The constructor must have the same name as the class.
You have to create:
public average(double a, double b, double c)
Actually the only constructor existing in the class is the constructor without arguments, that is created automatically.
You have not defined a constructor method that receives these arguments (3, 4, 6).
You have to create a constructor method like this:
public class average {
public double result
public average(int a, int b, int c){
this.result=this.takeaverage(double(a),double(b),double(c))
}
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave; }
}
If you only want to take the average of 3 numbers, you can do it without creating an average object. I have shown it below:
import java.util.*;
public class Ave {
public static void main(String[] args){
double number1, number2, number3;
Scanner console = new Scanner(System.in);
System.out.println("Enter number 1:");
number1 = console.nextDouble();
System.out.println("Enter number 2:");
number2 = console.nextDouble();
System.out.println("Enter number 3:");
number3 = console.nextDouble();
double average = (number1 + number2 + number3)/3;
System.out.println("The average is: " + average);
}
}
The above program asks the user for 3 numbers and prints out their average. Note that it is still a bit redundant. You can also modify it to ask for average of any numbers, like shown below:
import java.util.*;
public class Ave {
public static void main(String[] args){
int howMany;
double sum = 0.0;
double number, average;
Scanner console = new Scanner(System.in);
System.out.println("How many numbers do you want to take average of:");
howMany = console.nextInt();
int count = 1;
while(count <= howMany){
System.out.println("Enter number " + count);
number = console.nextDouble();
sum += number;
count++;
}
average = sum/howMany;
System.out.println("The average is: " + average);
}
}
You can modify the programs to take the average of 3 numbers without asking the user too, where the doubles number1, number2, and number3 will be given numbers (hard-coded, which is not a good practice in general).
You have created the "takeaverage" method but haven't invoked it. And maybe you should use a setter or pass the three numbers using the constructor and initialize and then only call the "takeaverage" method for a double value and get the average assigned to that double variable.
You need to use the default constructor and create the object from "average" class. Below is a very simple solution :
public class average {
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave;
}
}
//main class
public class ave{
public static void main(String []args){
average object = new average();
object.takeaverage(3,4,6);
}
}

How to call a method within a method

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.

Trouble with calling a method

I am having trouble with calling a method in the main of my program.
The program specifications are as follows:
setNoOfVehicles(): Returns the number of vehicles owned.
setWeeklyFuelCost(): Returns the average weekly cost of gas for all vehicles owned.
calcYearlyFuelCost(): Receives the average weekly fuel cost and returns the average annual fuel cost.
displayFuelCost(): Receives the number of vehicles owned, the average weekly fuel cost, and the average annual fuel cost.
main():
Calls setWeeklyFuelCost() and stores the returned value in a local variable.
Calls displayFuelCost() by sending it as arguments a call to setNoOfVehicles(), the local variable for the average weekly fuel cost, and a call to calcYearlyFuelCost().
Scanner is declared at the global level
public static void main(String[] args)
{
double x = setWeeklyFuelCost();
displayFuelCost( setNoOfVehicles(), x, calcYearlyFuelCost(x)); //This is the correct parameters I needed to pass thru displayFuelCost(). I didn't know this at the time and this is what I was trying to ask in this post.
}
private static int setNoOfVehicles()
{
System.out.print( "How many vehicles do I own? " );
int noOfVehicles = input.nextInt();
return noOfVehicles;
}
private static double setWeeklyFuelCost()
{
System.out.print( "Enter the average weekly fuel cost for my vehicles: ");
double weeklyFuelCost = input.nextDouble();
return weeklyFuelCost;
}
private static double calcYearlyFuelCost(double weeklyFuelCost)
{
double yearlyFuelCost = 0.0;
yearlyFuelCost = weeklyFuelCost * 52;
return yearlyFuelCost;
}
private static void displayFuelCost( int noOfVehicles, double weeklyFuelCost, double yearlyFuelCost)
{
double difference = yearlyFuelCost - 5044.00;
if( yearlyFuelCost > 5044.00)
{
System.out.printf( "No of Vehicles: %d\n"
+ "Avg Weekly Fuel Cost: $%,.2f\n"
+ "Avg Annual Fuel Cost: $%,.2f\n\n"
+ "I am OVER budget by $%,.2f.", noOfVehicles, weeklyFuelCost, yearlyFuelCost, difference);
}
else if( yearlyFuelCost < 5044.00)
{
difference = difference * -1;
System.out.printf( "No of Vehicles: %d\n"
+ "Avg Weekly Fuel Cost: $%,.2f\n"
+ "Avg Annual Fuel Cost: $%,.2f\n\n"
+ "I am UNDER budget by $%,.2f. PAARRTY!!! ", noOfVehicles, weeklyFuelCost, yearlyFuelCost, difference);
}
else
{
System.out.printf( "No of Vehicles: %d\n"
+ "Avg Weekly Fuel Cost: $%,.2f\n"
+ "Avg Annual Fuel Cost: $%,.2f\n\n"
+ "I am RIGHT ON BUDGET!", noOfVehicles, weeklyFuelCost, yearlyFuelCost, difference);
}
}
}
The last specification is the one holding me up, call displayFuelCost()
My problem was that I didn't know exactly what parameters I needed to pass through displayFuelCost(). I knew I had to use the variable x above before asking this question.
displayFuelCost( setNoOfVehicles(), x, calcYearlyFuelCost(x)); was all that I needed to input to get the main to work correctly.
You call a method displayFuelCost() which is not defined in your class. Instead you have a method
private static void displayFuelCost( int noOfVehicles, double weeklyFuelCost, double yearlyFuelCost) { ... }
that takes three parameters.
Change the method call to
displayFuelCost(1, 100.0, 5200.0); // sample values
to eliminate the error and get some result.
The code you pasted does not contain any class definition. If the main-method is in another class then the displayFuelCost-method, then you will have to change
private static void displayFuelCost( int noOfVehicles, double weeklyFuelCost, double yearlyFuelCost)
to public :
public static void displayFuelCost( int noOfVehicles, double weeklyFuelCost, double yearlyFuelCost)
That beeing said, I wouldn't recommend you this excessive usage of static methods. I don't see a reason why you shouldn't use proper object-oriented style (or at least a singleton-pattern, if it has to look static).
//EDIT:
The problem ist this part of your code:
public static void main(String[] args)
{
double x = setWeeklyFuelCost();
displayFuelCost(); //<-- need arguments here!
Inside your main function, you call the displayFuelCost-method, but do NOT provide the parameters it needs. When you have a look at the declaration of this method:
private static void displayFuelCost( int noOfVehicles, double weeklyFuelCost, double yearlyFuelCost)
}
You see that it needs 3 parameters: an integer, a double and another double. You have to provide them while calling the displayFuelCost function. For example like that:
public static void main(String[] args)
{
double x = setWeeklyFuelCost();
displayFuelCost(1, 2.5, 2.5); //<-- need parameters here!
}
//EDIT 2:
There are more problems in the whole code. I added an new answer concerning them.
Since I don't have the code of the scanner and the class I can not prove that my solution works, you have to try it out:
public class Test {
public static void main(String[] args) {
int vehicleNumber = setNoOfVehicles();
double costWeek = setWeeklyFuelCost();
double costYear = calcYearlyFuelCost(costWeek);
displayFuelCost(vehicleNumber, costWeek, costYear);
}
// rest of your code
}
But once again I have to warn you, that this is probably NOT what your teacher wants you to deliver. He wants a class that instantiates itself in the main method (e.g. Test test = new Test()) and than uses the instance-side methods (i.e. methods without static in the beginning) to fulfill the task. I would recommend you to try again. ;)

Categories

Resources