I am new To Java please help me, my local variable can't take me methods parameters.
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.text.DecimalFormat; //I can not get my local variables in my
// main to accept my methods parameters.
// This is my program.
public class AccountBank
{
public static void main (String[] args) throws IOException
{
// Calling in my Class
Accountclass BankAcc = new Accountclass();
// initialize both there variables in. order to use them in a for loop.
double depDrw = 0;// this are one of the variables that is giving me problems
double withDrw = 0; // this is the other that is giving me problems
double totalW = 0;
double totalD = 0;
// declaring all my variables
String name="";
double month;
double startBal;
// This section will greet and accept input by asking the user to enter the starting alance and set it in my class
// Greetings
JOptionPane.showMessageDialog(null,"Lets Get Started");
// receiving input for my name variable
name = JOptionPane.showInputDialog(null, "Please Enter Your Name Below: ");
// ask user for starting balance
startBal = Double.parseDouble(JOptionPane.showInputDialog("What Is The Starting Balance In Your Account:"));
// This will set the value in my class
BankAcc.setBal(startBal);
// ask user how many months has the account been active
month = Double.parseDouble(JOptionPane.showInputDialog("Months That Account Has Been Active:"));
// This section will accept input by asking the user to enter each amount deposited every month from the account set it in my class.
// This will be shown in the message box
depDrw = depositTotal(deposit); << // I am having trouble here it wont take my parameters variable which I created on the buttom. please help
// This will sum up every amount the user enters in the message box.
totalD += depDrw;
// This will set the value in my class
BankAcc.setdeposit(totalD);
// This section will accept input by asking the user to enter each amount withdrawn every month from the account and set it in my class
// This will be shown in the message box
withDrw = withdrawTotal(wit); // <<< I am having problem here this variable does not take the value of my methods parameter, which i created on the bottom of this page.
// This will sum up every amount the user enters in the message box.
totalW += withDrw;
// This will set the value in my class
BankAcc.setwithdraws(totalW);
//This section will display the " monthly interest rate, monthly interest earned, total amount deposited, total amount withdrawn, and the final balance of the account."
DecimalFormat formatter = new DecimalFormat("#0.0000");
DecimalFormat formatter2 = new DecimalFormat("#0.0");
DecimalFormat formatter3 = new DecimalFormat("#0.00");
//Get the calculations from the savings account class and display them.
JOptionPane.showMessageDialog(null," Account Name: " +name+"\n \n Your Monthly Interest Rate Is ..... "
+ formatter.format(BankAcc.monthInt())+"%" + "\n \n Your Monthly Interest Earned Was ..... $"
+ formatter2.format(BankAcc.GetInt()) + "\n \n Your Overall Amount With Deposited Was ..... $" + totalD +
" \n \n Your Overall Amount WithDrawn Was ..... $" + totalW + " \n \n Your Remaining Balance Is ..... $"
+ formatter3.format(BankAcc.getFinalbal()),"Results", JOptionPane.PLAIN_MESSAGE );
}
public static double depositTotal( String deposit)
throws IOException
{
double sales;
double totalDeposit = 0;
File file = new File ("deposits.txt");
Scanner inputfile = new Scanner(file);
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
inputfile.close();
return totalDeposit;
}
public static double withdrawTotal( String wit)
throws IOException
{
double sales;
double totalwithdraws = 0;
File file = new File ("withdraws.txt");
Scanner inputfile = new Scanner(file);
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalwithdraws += sales;
}
inputfile.close();
return totalwithdraws;
}
Your while loop is
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
There shouldn't be a ; after the while (inputfile.hasNextDouble())
while (inputfile.hasNextDouble())
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
Similarly for other while loops, remove the ;
Change your method declaration so it doesn't receive any parameter. And because it's returning a double, you may store the value it returns in a double variable:
double deposit = depositTotal();
In your depositTotal() method:
public static double depositTotal() throws IOException {
...
}
Related
I have this code. The askToContinue() method is being called to ask the user if they would like to continue but my problem is it just ignores the choice and starts the program again no matter what I enter. What am I missing in the code that is causing it to ignore my choice?
public class FutureValueApp {
public static void main(String[] args) {
System.out.println("Welcome to the Future Value Calculator\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("DATA ENTRY");
double monthlyInvestment = getDoubleWithinRange(sc,
"Enter monthly investment: ", 0, 1000);
double interestRate = getDoubleWithinRange(sc,
"Enter yearly interest rate: ", 0, 30);
int years = getIntWithinRange(sc,
"Enter number of years: ", 0, 100);
System.out.println();
// calculate the future value
double monthlyInterestRate = interestRate / 12 / 100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlyInvestment, monthlyInterestRate, months);
// print the results
System.out.println("FORMATTED RESULTS");
printFormattedResults(monthlyInvestment,
interestRate, years, futureValue);
System.out.println();
askToContinue(sc);
}
}
private static void printFormattedResults(double monthlyInvestment,
double interestRate, int years, double futureValue){
// get the currency and percent formatters
NumberFormat c = NumberFormat.getCurrencyInstance();
NumberFormat p = NumberFormat.getPercentInstance();
p.setMinimumFractionDigits(1);
// format the result as a single string
String results
= "Monthly investment: " + c.format(monthlyInvestment) + "\n"
+ "Yearly interest rate: " + p.format(interestRate / 100) + "\n"
+ "Number of years: " + years + "\n"
+ "Future value: " + c.format(futureValue) + "\n";
System.out.println(results);
}
public static String askToContinue(Scanner sc){
// see if the user wants to conti1nue
System.out.print("Continue? (y/n): ");
String choice = sc.next();
System.out.println();
return choice;
}
You're on the right track. Change this
askToContinue(sc);
to
choice = askToContinue(sc);
Because you need to assign the value returned from askToContinue to the local reference named choice.
You are not assigning the result of askToContinue to the choice variable which is checked in the loop.
Possibly the confusion is the choice variable inside the askToContinue method. Note, this is a different variable and does not affect the choice variable checked in the while statement.
When you define a variable inside a method, it is not recognized by the code outside of your method, even if it has the same name. So, in your code for example, you have,
public static String askToContinue(Scanner sc){
// see if the user wants to conti1nue
System.out.print("Continue? (y/n): ");
String choice = sc.next(); // this choice variable exists only for the
// askToContinue method
// Once you assign it over here and return it
// with the code below, you should use the returned
// value to update the variable choice, which is
// defined outside your askToContinue method
System.out.println();
return choice;
}
So, as the other answers have pointed out, if you do,
choice = askToContinue(sc);
then the code will run fine since the choice variable defined in the main method will get updated according to the value you input
Based on
John Camerin's answer,to skip double assigning in your code, you can make your choice variable as global static variable by define it in your class :
public class FutureValueApp {
public static String choice;
}
Or send it as second parameter in your method :
askToContinue(sc,choice);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I've only had a few hours practicing and learning Java so I'm still learning the basics.
I'm reading values from a text file, which contains:
Single
60
112.50
Master
70
2227.50
Penthouse
5
5000.00
(So it appears as when run)
Room Type: Single, Bookings: 60, Room Price: £112.00, Income: £6,750.00, Tax: 1350.00
And so fourth with each room.
I've printed all the values in a string format which is required. However, my problem is really simple.
I just want to add all the income together in a totalincome variable and add all the paidTax together in a totalpaidTax variable, then continue to print out it, to basically show the total tax paid and total income from all the rooms.
Although, I just don't know how to write it. I've had multiple attempts at trying but just no luck.
Here's my current code.
import java.io.FileReader;
import java.util.Scanner;
public class WagesCalculator {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
Scanner file = new Scanner(new FileReader("task3.txt"));
Scanner sc = new Scanner(System.in);
//Current tax variable value
double tax = 20;
//User Input Y or N to change tax variable value
System.out.println("- - Hotel Tax System - -");
System.out.print("Do you want to specify a custom Tax Rate? [Y|N]: ");
//if statement to change tax variable value subject to Y or N
if (sc.next().equalsIgnoreCase("Y")) {
System.out.print("Please enter the new tax value: ");
tax = new Scanner(System.in).nextInt();
}
//Prints out current tax value
System.out.println("The current tax rate is " + tax+".");
while (file.hasNext()) {
String name = file.next();
int numberOfBookings = file.nextInt();
double price = file.nextDouble();
double income = numberOfBookings * price;
double paidTax = income*(tax/100);
//String format print out final calculations
System.out.printf("Room Type: %s, Bookings: %d, Room Price: £%.2f, Income: £%.2f, Tax: %.2f %n", name, numberOfBookings, price, income, paidTax);
}
file.close();
}
}
Objects are your friend.
Create an object for each Room in your input.
Store the Rooms in a List.
Aggregate values from the List.
Print accordingly.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class WagesCalculator
{
public static void main(String[] args)
throws Exception
{
WagesCalculator wc = new WagesCalculator();
wc.calculate();
}
public void calculate()
throws FileNotFoundException
{
Scanner file = new Scanner(new FileReader("task3.txt"));
Scanner sc = new Scanner(System.in);
// Current tax variable value
double tax = 20;
// User Input Y or N to change tax variable value
System.out.println("- - Hotel Tax System - -");
System.out.print("Do you want to specify a custom Tax Rate? [Y|N]: ");
// if statement to change tax variable value subject to Y or N
if (sc.next().equalsIgnoreCase("Y"))
{
System.out.print("Please enter the new tax value: ");
tax = new Scanner(System.in).nextInt();
}
// Prints out current tax value
System.out.println("The current tax rate is " + tax + ".");
List<Room> rooms = new ArrayList<Room>();
while (file.hasNext())
{
String name = file.next();
int numberOfBookings = file.nextInt();
double price = file.nextDouble();
rooms.add(new Room(tax, name, numberOfBookings, price));
}
file.close();
rooms.stream().forEach(e -> System.out.println(e));
double totalIncome = rooms.stream().map(r -> r.income)
.reduce((a, b) -> a + b).orElse(0.0);
double totalTax = rooms.stream().map(r -> r.tax).reduce((a, b) -> a + b)
.orElse(0.0);
System.out.printf("Total income was: %d\nTotal tax was %d\n", totalIncome,
totalTax);
}
class Room
{
double tax;
String name;
int numberOfBookings;
double price;
double income;
double paidTax;
public Room(double tax, String name, int numberOfBookings, double price)
{
this.tax = tax;
this.name = name;
this.numberOfBookings = numberOfBookings;
this.price = price;
this.income = numberOfBookings * price;
this.paidTax = income * (tax / 100);
}
#Override
public String toString()
{
return String.format(
"Room Type: %s, Bookings: %d, Room Price: £%.2f, Income: £%.2f, Tax: %.2f %n",
name, numberOfBookings, price, income, paidTax);
}
}
}
I have been struggling with this issue for weeks and still cannot get what I need. My CalculatingRocketFlightProfile class holds the constructor with the parameters (totalImpulse, averageImpulse etc...) and the methods which calculates the outputs. My MAIN class has an object which inherits my keyboard entry class. This allows users to input a number. Now, all I need is to use these inputs and calculate a result (using the methods in the CalculatingRocketFlightProfile class) to be displayed. However my object of CalculatingRocketFlightProfile class wont acceppt any parameters or I simply doing something wronng. Please help me out I'm really frustrated.
//CalculatingRocketFlightProfile 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; //declare variables to store results of calculations
public double theVehiclesMaximumVelocity;
public CalculatingRocketFlightProfile(double totalImpulse, double averageImpulse, double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) { //Setting the parameters
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
//Mutators - SET
public void setTheAverageMassOfTheVehicle(double theAverageMassOfTheVehicle) {
this.theAverageMassOfTheVehicle = theAverageMassOfTheVehicle;
}//method
public void setTheVehiclesMaximumVelocity(double theVehiclesMaximumVelocity) {
this.theVehiclesMaximumVelocity = theVehiclesMaximumVelocity;
}//method
//Getters
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}//method
public double getTheVehiclesMaximumVelocity() {
return theVehiclesMaximumVelocity;
}//method
}//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.totalImpulse1());
System.out.print("\nPlease enter a number for Average Impulse: " );
System.out.println("You have entered : " +input.averageImpulse2());
System.out.print("\nPlease enter a number for Time ejection charge fires: " );
System.out.println("You have entered : " +input.timeEjectionChargeFires3());
System.out.print("\nPlease enter a number for the Mass of the vehicle: " );
System.out.println("You have entered : " +input.massEmptyVehicle4());
System.out.print("\nPlease enter a number for the Mass of the engine: " );
System.out.println("You have entered : " +input.engineMass5());
System.out.print("\nPlease enter a number for the Mass of the fuel: " );
System.out.println("You have entered : " +input.fuelMass6());
//Output
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(totalImpulse,averageImpulse,timeEjectionChargeFires,massEmptyVehicle,engineMass,fuelMass ); //This will give me an error "cant find variables"
System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() +
"\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity());
}
}
//kbentry class (Same for all methods e.g. averageImpulse2, timeEjectionChargeFires3 etc...)
public class kbentry{
double totalImpulse1(){
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
}
You are not storing the returned information from your kbentry methods. Try this:
System.out.print("\nPlease enter a number for Total Impulse: " );
double totalImpulse = input.totalImpulse1();
System.out.println("You have entered : " + totalImpulse);
Do the same for the other variables, then use those to pass in as arguments for your new object.
I am just beginning in Java and I am having a peculiar problem that I just cant seem to get to the root of. I have 2 programs and one is taking data from a text file and then calling it into a class to do some calculations and finally putting the output into another text document.
Everything works except this part here:
public class Paycheck
{
//Constants for the private class
private final String EMPLOYEE_NAME; //Employee name
private final String SOC_SEC_NUM; //Employee Social Security Number
private final double WAGE_RATE; //Employee wage
private final double TAX_RATE; //Employee tax withheld
private final double HOURS_WORKED; //Employee's hours of work
//Variables for the private class
private double grossPay; //Employee Gross Pay
private double taxWithheld; //Employee Tax Withheld
private double netPay; //Employee Net Pay
//This is the constructor. It is called whenever an instance of the class is created
public Paycheck (String name, String ssn, double wage, double tax, double hours)
{
EMPLOYEE_NAME = name; //Instance employee name
SOC_SEC_NUM = ssn; //Instance employee SSN
WAGE_RATE = wage; //Instance employee wage rate
TAX_RATE = tax; //Instance employee tax rate
HOURS_WORKED = hours; //Instance employee hours worked
}
//This calculates the variables in the paycheck class
public void calcWages()
{
grossPay = WAGE_RATE * HOURS_WORKED; //Calculates Gross Pay
taxWithheld = grossPay * TAX_RATE; //Calculates Taxes Withheld
netPay = grossPay - taxWithheld; //Calculates net pay
}
//Returns the Paycheck objects Employee Name
public String getEmployeeName()
{
return EMPLOYEE_NAME;
}
//Returns the employee SSN of the Paycheck object
public String getSocSecNum()
{
return SOC_SEC_NUM;
}
//Reeturns a Paycheck object's employee Wage Rate
public double getWageRate()
{
return WAGE_RATE;
}
//Returns a Paycheck object's employee tax rate
public double getTaxRate()
{
return TAX_RATE;
}
//Returns an Paycheck object's employee hours worked
public double getHoursWorked()
{
return HOURS_WORKED;
}
//Returns a Paycheck object's gross pay
public double getGrossPay()
{
return grossPay;
}
//Returns a Paycheck object's Taxes Withheld
public double getTaxWithheld()
{
return taxWithheld;
}
//Returns a paycheck object't net pay
public double getNetPay()
{
return netPay;
}
The calcWages() does the necessary calculations and below this are a series of get statements to call them. However, my output does not return any values for the calcWages() arguments.
I added the getters here and my other program is grabbing them. However the final output on my other program is coming up as 0.
Where am I going wrong here?
This is the part of the main method that is calling them
public static void main(String [] args) throws IOException //Throws clause
{
//Declare constants
final String INPUT_FILE = "Employee.txt"; //Input text file containing Employee information
final String OUTPUT_FILE= "PayrollHistory.txt"; //Output text file that will receive the data
//Declare Variables
String payPeriodDate; //Ending date of the pay period
String employeeName; //Employee Name in text file
String employeeSocSecNum; //Employee SSN in text file
double employeeHours; //Employee hours worked
double employeeTax; //Employee Tax rate
double employeeWage; //Employee Wage rate
double totalGrossPay; //Total employee Gross for pay period
double totalTaxWithheld; //Total Tax Withheld for pay period
double totalNetPay; //Total Net Payroll for pay period
String input; //String input for double conversion in JoptionPane
DecimalFormat money = new DecimalFormat ("#0.00"); // Decimal Format to put money in the right format(USD)
//This ensures that the input file actually exists in the program folder
//And exits the program if it does not, along with the prompt.
File file = new File(INPUT_FILE);
if (!file.exists())
{
JOptionPane.showMessageDialog(null, "The " + INPUT_FILE + " file cannot be found." +
"Program terminated.");
System.exit(0);
}
// Create Scanner object to enable reading data from input file
Scanner inputFile = new Scanner(file);
// Create FileWriter and PrintWriter objects to enable
// writing (appending not overwriting) data to text file
FileWriter fwriter = new FileWriter(OUTPUT_FILE, true);
PrintWriter outputFile = new PrintWriter(fwriter);
//Initialize accumulator values
totalGrossPay = 0.0;
totalTaxWithheld = 0.0;
totalNetPay = 0.0;
//Get the pay period for the employee
payPeriodDate = JOptionPane.showInputDialog("Enter pay period ending date (mm/dd/yyyy):");
outputFile.println("PAY PERIOD ENDING DATE: " + payPeriodDate); //Inputs pay period date into the text file
outputFile.println(); // Blank line
outputFile.println(); // Blank line
while (inputFile.hasNext()) // This will look through the input file and get the necessary variable input
{
// Read employee Name from Input File
employeeName = inputFile.nextLine();
// Read employee SSN from input file
employeeSocSecNum = inputFile.nextLine();
// Read employee Wage Rate from input file
//Parses it into a double type
input = inputFile.nextLine();
employeeWage = Double.parseDouble(input);
//Read employee tax rate from input file
//Parses it into a double type
input = inputFile.nextLine();
employeeTax = Double.parseDouble(input);
//Get number of hours worked
input = JOptionPane.showInputDialog("Employee Name: " + employeeName +
"\nEnter number of hours worked:");
employeeHours = Double.parseDouble(input);
//This call the paycheck class to create a new Paycheck Object
Paycheck employee = new Paycheck (employeeName, employeeSocSecNum, employeeWage, employeeTax, employeeHours);
// Call Paycheck class methods into the output file
outputFile.println("Employee Name: " + employeeName); //Employee Name
outputFile.println("SSN: " + employeeSocSecNum); //Employee SSN
outputFile.println("Hours Worked: " + employeeHours); //Employee Hours Worked
outputFile.println("Wage Rate: " + money.format(employeeWage)); //Employee Wage Rate
outputFile.println("Gross Pay: " + money.format(employee.getGrossPay())); //Employee Gross Pay
outputFile.println("Tax Rate: " + money.format(employeeTax)); //Employee Tax Rate
outputFile.println("Tax Withheld: " + money.format(employee.getTaxWithheld())); //Employee Tax Withheld
outputFile.println("Net Pay: " + employee.getNetPay()); //Employee Net Pay
outputFile.println(); // Blank line
You don't appear to be actually calling calcWages() before calling your getters, so grossPay, taxWithheld, and netPay are still going to be 0, as that's Java's default value for uninitialized numbers.
You need to call employee.calcWages() before referencing those values for them to change.
It is because calcWages() is declared void (public void calcWages()), meaning it is not supposed to return any value but just complete a series of steps (calc payroll particulars in this example). After calling it, just proceed to reference the instance variables it processed.
You have declared your variables as final, meaning they can only be assigned once.
The assignment is:
Write a program that provides 20% discount for member who purchase any two books at XYZ bookstore. (Hint: Use constant variable to the 20% discount.)
I have done the coding, but cannot prompt book name, and then show the discounted price. Please see my coding below and modify it as your needs.
import java.util.Scanner;
public class Book_Discount {
public static void main(String args[]) {
public static final double d = 0.8;
Scanner input = new Scanner(System.in);
int purchases;
double discounted_price;
System.out.print("Enter value of purchases: ");
purchases = input.nextInt();
discounted_price = purchases * d; // Here discount calculation takes place
// Displays discounted price
System.out.println("Value of discounted price: " + discounted_price);
}
}
For prompting the book name as well, you write something like:
/* Promt how many books */
System.out.print("How many books? ");
int bookCount = scanner.nextInt();
scanner.nextLine(); // finish the line...
double totalPrice = 0.0d; // create a counter for the total price
/* Ask for each book the name and price */
for (int i = 0; i < bookCount; ++i)
{
System.out.print("Name of the book? ");
String name = scanner.nextLine(); // get the name
System.out.print("Price of the book? ");
double price = scanner.nextDouble(); // get the price
scanner.nextLine(); // finish the line
totalPrice += price; // add the price to the counter
}
/* If you bought more than 1 book, you get discount */
if (bookCount >= 2)
{
totalPrice *= 0.8d;
}
/* Print the resulting price */
System.out.printf("Total price to pay: %.2f%n", totalPrice);