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. ;)
Related
So currently, I'm struggling to make one particular program in eclipse for an assignment, while I am able to make most of the program, I seem to struggle with the no argument part of the program as well as bringing the pieces of the first class into the second for a brief moment. Here is my code for the first class
// Preparation of the input
import java.util.Scanner;
public class primarySetUp {
public static void main(String[] args) {
// Variable Declaration
double userBagNumber;
double userBagWeight;
// Create Scanner
Scanner input = new Scanner(System.in);
java.util.Date date = new java.util.Date();
// Opening Statement
System.out.println("Welcome to the Coffee Sales Simulation!");
// Get User Input
System.out.println("How heavy do you want the bags to be?");
userBagWeight = input.nextDouble();
System.out.println("How many bags do you want?");
userBagNumber = input.nextDouble();
// Get output
// Date
System.out.println("Todays date: ");
System.out.printf("%tB %<te, %<tY", date);
System.out.println(""); // spacer
// Original Inputs
System.out.printf("\nNumber of Bags: %3.0f", userBagNumber);
System.out.printf("\nWeight of Each Bag: %3.2f", userBagWeight);
System.out.print(" lbs");
// Calling of the Class
secondarySetUp mysecondarySetUp = new secondarySetUp(userBagWeight, userBagNumber);
// End Program
System.out.println("\nThank you for shopping with us!");
}
}
and here is my code for the second class, which is full of errors in this case.
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
public secondarySetUp(double userBagWeight, double userBagNumber) {
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// No argument pricing
public Sale() {
singleBagger = 1;
pounderBagger = 1;
}
// First constructor receiving No argument pricing
public Sale(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
If you have any sort of fixes I could apply, please let me know; I am planning on adding the print statements for the rest of the arguments as well, but I'd like to get Sale() fixed up first.
I see a problem in getSale() where you are trying to use userBagWeight, but that variable doesn't exist outside the constructor parameters, which could create a lot of problems since other methods are calling on it. The constructor taking
double userBagWeight, double userBagNumber, yet it's not assigning them to any fields or doing anything with them.
I missed the part where you are treating Sale() as a constructor, but those are no constructors. The constructor is named after your class name.
public secondarySetUp(double userBagWeight, double userBagNumber)
change Sale() to secondarySetUp and you will be fine.
here how your class should be like :
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
double userBagWeight, userBagNumber;
public secondarySetUp(double userBagWeight, double userBagNumber) {
this.userBagWeight = userBagWeight;
this.userBagNumber = userBagNumber;
singleBagger = 1;
pounderBagger = 1;
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// First constructor receiving No argument pricing
public secondarySetUp(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
this is a keyword to tell the program that we want to use the field "instance variable", if we have a method with parameter that have same name as a field name, then to tell them apart we tell the program this.fieldName to know which one we talking about.
I think I did it all correct however im having an error. Very confused.
Error: overtime.java:10: error: variable pay might not have been initialized
displayResults(pay);
Code:
import java.util.Scanner;
public class Overtime {
public static void main(String[] args) {
int hours;
double rate, pay;
Scanner in = new Scanner(System.in);
displayResults(pay);
System.out.println();
System.out.print( "Enter how many hours worked: " );
hours = in.nextInt();
System.out.print( "Enter hourly rate: " );
rate = in.nextDouble();
}
public double calculatePay( int hours, double rate, double pay ) {
if ( hours > 40 ) {
int extraHours = hours - 40;
pay = ( 40 * rate ) + ( extraHours * rate * 1.5);
} else
pay = hours * rate;
return pay;
}
public static void displayResults(double pay) {
System.out.printf( "\nGross Salary: %f", pay);
}
}
The code inside your main has to reordered:
public static void main(String[] args) {
int hours;
double rate, pay;
Scanner in = new Scanner(System.in);
System.out.print( "Enter how many hours worked: " );
hours = in.nextInt();
System.out.print( "Enter hourly rate: " );
rate = in.nextDouble();
pay = ;// call calculatePay here
displayResults(pay);
}
And you have to remove the pay parameter of the calculatePay method. Its declaration should be
public static double calculatePay( int hours, double rate )
The reason you get this error is the fact you didn't assign any value to variable payand you called a method displayResults() which needs this variable as an argument. Firstly you should calculate pay value with calculatePay (but you should delete double pay from list of arguments passed to this method, because there is no need to place it there).
After calculations made with calculatePay() and having its result in pay variable you can call displayResults() without problem.
Another problem is that calculatePay() need to made static and both your methods should be declared outside of the main() method body (the bold part of my answer is no longer relevant, because bad looking indentation made me a bit confused and I thought that methods were declared inside the main() method).
This looks a bit like a homework. So Iam providing only guidance:
Initialize all variables first and set them to values. (eg. double pay=1; ) and drop the Scanner.
Once this is working - add the Scanner and display all variables with System.out.format(...).
Once vars are displayed properly (point2) and (1)works - connect variables set by the Scanner with rest of your code
Good luck! :-)
I am trying to do the calculations for the interest in another method, and I know that I have to make another method outside of main and then put return an the end, but I have no idea what to title this new method and how to go about doing the calculations there. I think it is the while loop that is confusing me. I have done this once before on a different project, so I have an idea of how to do it, but this project isn't anything like the other one and I don't really understand it. Any help is extremely appreciated as I have been working on this for a long time and just want to get it over with. Thanks in advance.
import java.util.Scanner; // This allows for the use of the scanner in the class
public class SavingsAccount // Start of class
{
public static void main(String[]args) // Start of main
{
double P; // These store the amounts that will be used in the accruing interest formula
double i;
double n;
double S = 0;
int timesLooped = 0;
Scanner readConsole = new Scanner(System.in); // This is the scanner
System.out.println("I am a savings account interest calculator."); // Prompts the user for input
System.out.println("How much money have you deposited?");
P = readConsole.nextDouble();
S = P;
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
i = readConsole.nextDouble();
System.out.println("Finally, how long do you plan on having the money in the account?");
n = readConsole.nextDouble();
while (timesLooped <= n)
{
S = S + (P * i);
timesLooped += 1;
}
System.out.println("Your balance in that time span is " + S + "."); // Tells you your ending balance
}
}
Based on your comment, I think you want this:
private static double addInterest(double S, double P, double i)
{
return S + (P * i);
}
...
public static void main()
{
...
while (timesLooped <= n)
{
S = addInterest(S, P, i);
}
EDIT
I made some small improvements just for fun:
I put the entire interest calculation into the function and used exponentiation rather than a loop.
I gave the variables more descriptive names.
I used System.out.format to print the result.
Here's the code:
private static double computeCompoundInterest(double principal, double rate,
double years) {
return principal * Math.pow(1 + rate, years);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("I am a savings account interest calculator.");
System.out.println("How much money have you deposited?");
double principal = scanner.nextDouble();
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
double rate = scanner.nextDouble();
System.out.println("How many years will you hold that money in the account?");
double years = scanner.nextDouble();
double total = computeCompoundInterest(principal, rate, years);
System.out.format("Your balance at the end of that period will be %.2f.\n", years, total);
}
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);
}
}
I'm having a little bit of a problem with this exercise and I was wondering if anyone could help. here is the problem:
Create a class named Purchase. Each Purchase contains an invoice number, amount of sale, and amount of sales tax. Include set methods for the invoice number and sale amount. Within the set() method for the sale amount, calculate the sales tax as 5% of the sale amount. Also include a display method that displays a purchase’s details. Save as Purchase.class
b. Create an application that declares a Purchase object and prompts the user for purchase details. When you prompt for an invoice number, do not let the user proceed until a number between 1,000 and 8,000 has been entered. When you prompt for a sale amount, do not proceed until the user has entered a nonnegative value. After a valid Purchase object has been created, display the object’s invoice number, sale amount, and sales tax.
Here's my code for my Purchase class
import javax.swing.JOptionPane;
import java.util.Scanner;
public class Purchase
{
//variables
public static int invoice;
public static double saleAmount;
public static double saleTax;
//get&set for Invoice
public void setInvoice(int x)
{
invoice = x;
}
public int getInvoice( )
{
return invoice;
}
//get&set for saleAmount
public void setSaleAmount(double y)
{
saleTax = y * 0.05;
saleAmount = y;
}
public double getSaleAmount( )
{
return saleAmount;
}
//get for saleTax
public double getSaleTax( )
{
return saleTax;
}
//display method
public void display(int invoice, double saleAmount, double saleTax)
{
System.out.println("Invoice number: " + invoice + '\n' + "Sale's Amount: " + saleAmount + '\n' + "Sale's Tax: " + saleTax);
}
}
And the code for the CreatePurchase class
import javax.swing.JOptionPane;
import java.util.Scanner;
public class CreatePurchase
{
public static void main(String[] args)
{
Purchase purchase1 = new Purchase ();
//scanner for sales amount
Scanner inputDevice = new Scanner(System.in);
System.out.println("Please enter the sale amount: ");
Purchase.saleAmount = inputDevice.nextDouble();
//loop for saleAmount
while (Purchase.saleAmount < 1)
{
System.out.print('\n'+ "Error, your sale amount needs to be more than 0. Please enter a valid sale amount: >> ");
Purchase.saleAmount = inputDevice.nextDouble();
}
//scanner for invoice
System.out.println("Please enter an invoice number between 1000 and 8000: ");
Purchase.invoice = inputDevice.nextInt();
//loop for invoice
while (Purchase.invoice < 999 || Purchase.invoice > 8000)
{
System.out.print('\n'+ "Error, please enter a valid invoice number between 1000 and 8000: >> ");
Purchase.invoice = inputDevice.nextInt();
}
//display result
JOptionPane.showMessageDialog(null, "Your invoice number is " + Purchase.invoice + '\n'
+ "Your sale tax is: " + Purchase.saleTax + '\n'
+ "Your grand total is: " + Purchase.saleAmount);
}
}
As you can see, when you run the second class, the saleAmount doesn't include the extra 5% for sale tax and sale tax remains as 0. Is probably something really silly, but I have no idea where to start.
The definition of invoice, saleAmount and saleTax as public static defeats the purpose of object oriented programming.
They should be private instance variables, and you should access and modify them by calling the get and set methods on the instance you create (purchase1). Otherwise there's no point in defining those setters and getters, and there's no point in creating this instance, which you never use.
1) Convert your Static class variables into Instance Variables.
private int invoice;
private double saleAmount;
private double saleTax;
2) Then use Getter/Setter on your Purchase object
purchase1.setSaleAmount();
purchase1.getSaleAmount();
Note: Static fields do not recognize Object instances. If want to have multiple Purchase objects, your variables should be Instance variables and not class(static) variables.
The saleTax is calculated by the setSaleAmount method. You never call this method, so the saleTax is never calculated.
Instead of:
Purchase.saleAmount = inputDevice.nextDouble();
you probably want:
purchase1.setSaleAmount(inputDevice.nextDouble());
You may also want to read through some texts that explain the difference between classes and objects, and between static and instance members. But by changing that one line of code the program will at least work.