Calling a calculated variable from a class - java

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.

Related

Compound interest

import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually, monthly, daily;
double balance;
int year = 10 ;
System.out.println("Enter the amount you will like to deposit or type exit to end.");
int deposit = key.nextInt();
annually = deposit * Math.pow((1 + rate/1),year);
monthly = deposit * Math.pow((1 + rate/12),year);
daily = deposit * Math.pow((1 + rate/365),year);
while (deposit)
{
}
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
This is what I currently have. What I am trying to accomplish is to make a loop to add the first outcome with the next one. Also make one formula instead of having three to find the annually, monthly and daily.
First and foremost, asking someone to write out your homework is really unethical, and not helpful for you in the long run. If you don't care about the long run, consider taking a different class. In a career scenario, you're expected to write code on your own.
Secondly, to actually answer your question, here are some tips:
It seems like you want to gather a value (deposit) from the user, and then calculate the Compound Interest for said value. Your program also needs to not exit until the user says to exit. i.e. they want to calculate the CI for a set of numbers.
First step is to check the value from the user. If it is a number, then do calculations on it. If it is a String, then check if it is "exit". In Java, this amounts to writing out an if-statement, and making use of the very helpful "instanceof" keyword. If you haven't learned about that, give this a read, or ask your teacher.
For the calculations part, you simply do calculations on the user's input while the input is not a string set to "exit".
Finally, print out your calculations.
That's it. Your code already has the calculation formulas down, so you just need to code the logic for handling user input.
import java.util.Scanner;
import java.lang.Math;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How much money you want to deposit?");
int principle = sc.nextInt();
System.out.println("what is the rate you want?");
float rate = sc.nextFloat();
System.out.println("After how many years, you want to see your money?");
int year = sc.nextInt();
System.out.println("How many compounds in a year?");
int partialTime = sc.nextInt();
double b = year * partialTime;
double a = 1 + (rate/(partialTime*100));
double x = principle * (Math.pow(a,b));
System.out.println("Your interest in given time would be " + x);
}
}
A couple of suggestions - since you want to check user input against both String and int types, you could define a String type variable to hold the user input, and then do a try/catch to parse it as an Integer, if it's not an Integer check if the input equals "exit" (using the String.equals() method).
import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually = 0, monthly = 0, daily = 0;
double balance;
int year = 10, deposit = 0 ;
String userinput = "";
do {
try {
System.out.println("Enter the amount you will like to deposit or type exit to end.");
userinput = key.nextLine();
deposit = Integer.parseInt(userinput);
}
catch (Exception e){
if (!userinput.equals("exit")){
System.out.println("Didn't recognize that input, please try again...");
}
else{
break;
}
}
} while (!userinput.equals("exit"));
annually += deposit * Math.pow((1 + rate/1),year);
monthly += deposit * Math.pow((1 + rate/12),year);
daily += deposit * Math.pow((1 + rate/365),year);
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
Depending on how you want the output, you can easily adjust the scope of the loop to display the amounts after each valid deposit input, or just once at the end, after the user enters "exit".
Hope this helps.

Object oriented programming, getter is not getting private variable from another class

The program is supposed to calculate interest for 2 accounts after 12 and 24 months. This works fine. My issue is the getter/setter for interest rate do not work, so when the interest rate is saved as 0.1 in another class private variable I can't print it from main class.
public class testAccountIntrest{
//main method
public static void main(String[] args) {
//creating objects
Account account1 = new Account(500);
Account account2 = new Account(100);
//printing data
System.out.println("");
System.out.println("The intrest paid on account 1 after 12 months is " + account1.computeIntrest(12));
System.out.println("");
System.out.println("The intrest paid on account 1 after 24 months is " + account1.computeIntrest(24));
System.out.println("");
System.out.println("");
System.out.println("The intrest paid on account 2 after 12 months is " + account2.computeIntrest(12));
System.out.println("");
System.out.println("The intrest paid on account 2 after 24 months is " + account2.computeIntrest(24));
System.out.println("");
System.out.println("The intrest rate is " + getIntrest());
}//end main method
}//end main class
class Account {
//instance variables
private double balance;
private double intrestRate = 0.1;
//constructor
public Account(double initialBalance) {
balance = initialBalance;
}
//instance methods
public void withdraw(double amount) {
balance -= amount;
}
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
public void setIntrest(double rate) {
intrestRate = rate;
}
public double getIntrest() {
return intrestRate;
}
public int computeIntrest(int n) {
double intrest = balance*Math.pow((1+intrestRate),(n/12));
return (int)intrest;
}
}
As the compiler is undoubtedly telling you, your testAccountIntrest class doesn't have a method called getInterest(). So this alone can't do anything in the context of that class:
getInterest()
However, your Account class does have that method. And you have two Account objects in that scope:
Account account1 = new Account(500);
Account account2 = new Account(100);
So you can call that method on those objects:
account1.getInterest()
or:
account2.getInterest()
Basically, you have to tell the code which object you're calling the method on. It can't figure it out on its own.
getIntrest() is a member method, therefore you need to call
System.out.println("The intrest rate for account 1 is " + account1.getIntrest());
System.out.println("The intrest rate for account 2 is " + account2.getIntrest());
To call a method from another class you need an object of another class.
So, you need an instance of account to call getIntrest. For example:
System.out.println("The intrest rate for account 1 is " + account1.getIntrest());
If an interest rate is the same for all accounts you can make it static:
private static double intrestRate = 0.1;
public static double getIntrest() {
return intrestRate;
}
Static fields belong to the class and you don't need a specific instance to access it:
System.out.println("The intrest rate for all accounts is " + Account.getIntrest());

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.

Serialization difficulty

I have had a good look in books and the internet but cannot find a solution to my specific problem.Im really worried as time is running out.
I am writing code for an account. Each transaction, if it is add or withdraw is an object. Information such as the add amount, withdraw amount, transaction number,balance and total spending in a particular category is an object. Each object is stored in an arrayList. There is also code for logging in because this will eventually be an app. It requires the user to input their student number(last 4 digits).
The code runs ok and it serializes on termination. Upon running the code i can see it has de serialized the file as there is a list of objects in the arrayList printed.
My problem is that the values such as student number and balance are 0 when the code runs.Also the transaction number does not increment. It does increment while the code runs but stops upon termination, starting at 1 when the code is run again.
I expected all values to be the same when de serailized as those in the last object in the arrayList before serialization.
I dont expect anyone to post the answer but if someone could point me in the right direction i could try to work it out myself.
Best regards
Richard
PS. transaction number is the first in the object, balance in the middle and student number the four digits at the end. I have added the main class and serialization class, if anyone wants to see the login, transaction or other classes i can post these too.
`
/**
* Created by Richard on 16/07/2014.
*/
public class AccountTest implements Serializable {
public static Scanner keyboard = new Scanner(System.in);
//Declare an ArrayList called 'transactions' which will hold instances of AccountInfo.
public static ArrayList transactions = new ArrayList<AccountInfo>();
//Declare and initiate variables relating to the AccountTest class.
private static int transactionNum = 0;
private static double depositAmount = 0;
public static double withdrawAmount = 0;
private static double currentBalance = 0;
// A method which prompts the user to either withdraw, add funds or quit,
//this method also updates the balance and transaction number.
public static void addOrSpend() {
do {//A do while loop to ensure that the method repeatedly asks the user for input.
System.out.println("Enter a 1 to deposit, 2 to withdraw, 3 to terminate:");
int choice = keyboard.nextInt();
if (choice == 1) {//The deposit choice that also sets transaction no. and the balance.
System.out.println("Enter an amount to deposit ");
depositAmount = keyboard.nextInt();
transactionNum = transactionNum + 1;
withdrawAmount = 0;
currentBalance = currentBalance + depositAmount;
//System.out.println("You entered: " + depositAmount);
}//if
if (choice == 2) {//The withdraw choice that also sets transaction num, balance and calls chooseCategory method.
System.out.println("Enter an amount to withdraw ");
withdrawAmount = keyboard.nextInt();
transactionNum = transactionNum + 1;
depositAmount = 0;
currentBalance = currentBalance - withdrawAmount;
AccountCategory.chooseCategory();
}//if
if (choice == 3) {//User option to quit the program.
AccountSerialize.serialize();
System.out.println("App terminated...");
System.exit(1);
}//if
AccountInfo acc = new AccountInfo();//creates an object of the AccountInfo class
//Setters for the various methods in the AccountInfo class,
// these initiate variables for instances of the class.
acc.setTransactionNum(transactionNum);
acc.setDepositAmount(depositAmount);
acc.setWithdrawAmount(withdrawAmount);
acc.setCurrentBalance(currentBalance);
acc.setAccommodation(AccountCategory.accommodation);
acc.setTransport(AccountCategory.transport);
acc.setUtilities(AccountCategory.utilities);
acc.setEntertainment(AccountCategory.entertainment);
acc.setEssentials(AccountCategory.essentials);
acc.setStudentNo(AccountLogin.studentNo);
transactions.add(acc);//Adds each new 'acc' object to the ArrayList 'transaction'.
//System.out.println("List:" + transactions);Unused print statement which shows contents of ArrayList for testing.
Formatter x = new Formatter();//Series of formatted print statements which allow the information to be displayed in tabular format with headings.
System.out.println(String.format("%-20s %-20s %-20s %-20s ", "Transaction No.", "Deposit amount", "Withdraw amount", "Current balance"));
System.out.println(String.format("%-20s %-20s %-20s %-20s", transactionNum, depositAmount, withdrawAmount, currentBalance));
System.out.println(String.format("%-20s %-20s %-20s %-20s %-20s ", "Accommodation", "Transport", "Utilities", "Entertainment", "Essentials"));
System.out.println(String.format("%-20s %-20s %-20s %-20s %-20s", AccountCategory.accommodation, AccountCategory.transport, AccountCategory.utilities,
AccountCategory.entertainment, AccountCategory.essentials));
} while (transactions.size() >= 0);//End of do while statement that repeatedly prompts the user.
}
//Main method from where the program starts and user logs in. Starts with request for user to login.
// This then allows the user to continue with the program.
public static void main(String args[]) {
AccountSerialize.deSerialize();
System.out.println("Testing to see if student num is saved, login is..." +AccountLogin.studentNo );
System.out.println("Testing to see if balance is saved, balance is..." +currentBalance );
if (AccountLogin.studentNo == 0)
{
AccountLogin.numberSave();
}
else
{
AccountLogin.login();
}
}//main
}//class AccountTest
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Richard on 24/07/2014.
*/
public class AccountSerialize {
public static String filename = "budgetApp.bin";
public static String tmp;
public static void serialize() {
try {
FileOutputStream fos = new FileOutputStream("budgetApp.bin");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(AccountTest.transactions);
oos.close();
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Done writing");
}//serialize()
public static void deSerialize(){
try
{
FileInputStream fis = new FileInputStream("budgetApp.bin");
ObjectInputStream ois = new ObjectInputStream(fis);
AccountTest.transactions = (ArrayList) ois.readObject();
ois.close();
fis.close();
}catch(IOException ioe){
ioe.printStackTrace();
return;
}catch(ClassNotFoundException c){
System.out.println("Class not found");
c.printStackTrace();
return;
}
for( Object tmp:AccountTest.transactions){
System.out.println(tmp);
}
}//deSerialize()
}//class
import java.util.Scanner;
/**
* Created by Richard on 22/07/2014.
*/
public class AccountCategory {
static Scanner keyboard = new Scanner(System.in);
//Declare and initiate variable to be used in this class.
public static double accommodation = 0;
public static double transport = 0;
public static double utilities = 0;
public static double entertainment = 0;
public static double essentials = 0;
//A method which prints a set of spending category choices and asks the user to choose.
//Also updates each category variable with the total amount spent in that category
public static void chooseCategory() {
System.out.println("Please choose a category of spending, enter corresponding number");
System.out.println("1:\tAccommodation \n2:\tTransport \n3:\tUtilities \n4:\tEntertainment " +
"\n5:\tEssentials ");
double choice = keyboard.nextInt();//User input.
if (choice == 1) {
accommodation = accommodation + AccountTest.withdrawAmount;
}//if
if (choice == 2) {
transport = transport + AccountTest.withdrawAmount;
}//if
if (choice == 3) {
utilities = utilities + AccountTest.withdrawAmount;
}//if
if (choice == 4) {
entertainment = entertainment + AccountTest.withdrawAmount;
}//if
if (choice == 5) {
essentials = essentials + AccountTest.withdrawAmount;
}//if
}//chooseCategory
}//Class AccountCategory
import java.io.Serializable;
import java.util.Scanner;
/**
* Created by Richard on 16/07/2014.
*/
public class AccountInfo implements Serializable {
//Declare variables for types of transaction, balance and categories of spending.
public int studentNo;
public int transactionNum;
public double depositAmount;
public double withdrawAmount;
public double currentBalance;
public double accommodation;
public double transport;
public double utilities;
public double entertainment;
public double essentials;
//Series of mutator methods which take and validate the user input from the Test class, setting new variable values
//for objects of this AccountInfo class.
public void setStudentNo(int studentNo) {
this.studentNo = studentNo;
}
public void setTransactionNum(int transactionNum) {
this.transactionNum = transactionNum;
}
public void setDepositAmount(double depositAmount) {
this.depositAmount = depositAmount;
}
public void setWithdrawAmount(double withdrawAmount) {
this.withdrawAmount = withdrawAmount;
}
public void setCurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
}
public void setAccommodation(double accommodation) {
this.accommodation = accommodation;
}
public void setTransport(double transport) {
this.transport = transport;
}
public void setUtilities(double utilities) {
this.utilities = utilities;
}
public void setEntertainment(double entertainment) {
this.entertainment = entertainment;
}
public void setEssentials(double essentials) {
this.essentials = essentials;
}
//A toString method to ensure printed information is user readable
public String toString() {
return "AccountInfo[" + transactionNum + "," + depositAmount + "," + withdrawAmount + "," + currentBalance + "," +
accommodation + "," + transport + "," + utilities + "," + entertainment + "," + essentials + ","+studentNo+"]";
}//toString
}//class AccountInfo
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Created by Richard on 20/07/2014.
*/
public class AccountLogin {
public static Scanner keyboard = new Scanner(System.in);
//Declare and initiate variables.
public static int studentNo=0;
public static int login=0;
public static void login() {
if (studentNo > 0 && Integer.toString(studentNo).length() == 4)//Validation test.
{
System.out.println("Log in with last four digits of your student number:");
login = keyboard.nextInt();//User input.
}//if
if(login==studentNo){
AccountTest.addOrSpend();//If validated
}//if
else{
enterNoAgain();
}//else
}//login()
//This method checks to see if the user has already entered and saved their details, if not the user is prompted to do so.
//If the user has already entered their details
public static void numberSave() {
if (studentNo == 0) {//Checks to see if student number has already been entered.
System.out.println("Enter and save the last four digits of your student number, use this to login to the Budgeting app:");
studentNo = keyboard.nextInt();//User input.
if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Checks that user input meets requirements.
System.out.println("You are now logged in:");
AccountTest.addOrSpend();//Program starts at this point once user input is validated.
}//if
else {//If user input does not meet criteria, the following method is called.
enterNoAgain();
}//else
}//if
}//numberSave()
// This method takes over if the user has not input valid data.
// The user is instructed to do so and is given a further 2 opportunities before the program exits
public static void enterNoAgain() {
System.out.println("Invalid input: Use 4 numbers only, try again");//Prompt.
studentNo = keyboard.nextInt();//User input.
if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Validation test.
AccountTest.addOrSpend();//If validated
}//if
else {
System.out.println("Last attempt, input last four digits of your student number");//Prompt.
studentNo = keyboard.nextInt();//User input.
if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Validation test.
AccountTest.addOrSpend();//If validated
}//if
else {
AccountSerialize.serialize();//Save to file
System.out.println("You failed to login");
System.out.println("App terminated...");
System.exit(1);//Program exits due to invalid user input.
}//else
}//else
}//enterNoAgain()
}//class AccountLogin
`
AccountTest
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,50.0,0.0,50.0,0.0,0.0,0.0,0.0,0.0,3333]
AccountInfo[1,50.0,0.0,50.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,6666]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,50.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,500.0,0.0,500.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,0.0,0.0,50.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,50.0,0.0,0.0,0.0,0.0,1234]
Testing to see if student num is saved, login is...0
Testing to see if balance is saved, balance is...0.0
Enter and save the last four digits of your student number, use this to login to the Budgeting app:
1234
You are now logged in:
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
1
Enter an amount to deposit
1000
Transaction No. Deposit amount Withdraw amount Current balance
1 1000.0 0.0 1000.0
Accommodation Transport Utilities Entertainment Essentials
0.0 0.0 0.0 0.0 0.0
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
2
Enter an amount to withdraw
50
Please choose a category of spending, enter corresponding number
1: Accommodation
2: Transport
3: Utilities
4: Entertainment
5: Essentials
1
Transaction No. Deposit amount Withdraw amount Current balance
2 0.0 50.0 950.0
Accommodation Transport Utilities Entertainment Essentials
50.0 0.0 0.0 0.0 0.0
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
3
Done writing
App terminated...
Process finished with exit code 1

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