Initialization and FileNotFoundException errors - java

I am a new Java student and am writing a program that consists of a main method, a class file, two input .txt files, and an output.txt file. The main method should ask the user what the account balance and annual interest is and import deposit and withdrawal information from their respective files, and then to display all calculations from the class file in an output file.
I had originally written this file to ask users for all of this input using the scanner and now I'm trying to get it to work using files as input...which is not going so well.
Main method:
import java.util.Scanner;
import java.io.*;
public class SavingsAccountDemo {
public static void main(String[] args) {
//declare variables
double interest;
double startAmount;
double amountDeposit;
double amountWithdraw;
double d, w;
String filenameInputW, filenameInputD, filenameOutput;
PrintWriter oFile;
File wFile, dFile;
Scanner iFile;
Scanner key = new Scanner(System.in);
//get initial balance
System.out.println("Enter initial account balance: ");
startAmount = key.nextDouble();
//create SavingsAccount class object sending starting amount to constructor
SavingsAccount money = new SavingsAccount(startAmount);
//get annual interest rate
System.out.println("Enter annual interest rate: ");
interest = key.nextDouble();
//send interest rate to class
money.setInterest(interest);
//Retrieve withdrawals from withdrawal.txt
filenameInputW="withdrawal.txt";
wFile = new File (filenameInputW);
iFile = new Scanner (wFile);
while(iFile.hasNext())
{
double num;
num=iFile.nextDouble();
amountWithdraw += num;
if(amountWithdraw >= 0.1)
w++;
}
//send to SavingsAccount class
money.withdraw(amountWithdraw);
//Retrieve deposits from deposit.txt
filenameInputD="deposit.txt";
dFile = new File (filenameInputD);
iFile = new Scanner (dFile);
while(iFile.hasNext())
{
double num;
num=iFile.nextDouble();
amountDeposit += num;
if (amountDeposit >= 0.1)
d++;
}
//send to SavingsAccount class
money.deposit(amountDeposit);
//display retults
filenameInputW="output.txt";
oFile=new PrintWriter (filenameOutput);
oFile.println("The ending balance is: " + money.getBalance());
oFile.println("The total amount of withdrawls are: " + w);
oFile.println("The total amount of deposists are: " + d);
oFile.println("The annual interest rate is: " + money.getInterest());
}
}
My class file
/**
* #(#)SavingsAccount.java
*
*
* #author
* #version 1.00 2013/5/6
*/
public class SavingsAccount {
//variables
private double interest;
private double balance;
//Constructor
public SavingsAccount(double b)
{
balance = b;
interest = 0.0;
}
//Accessors
public void setInterest(double i)
{
interest = i;
}
public void setBalance(double b)
{
balance = b;
}
//Mutators
public double getInterest()
{
return interest;
}
public double getBalance()
{
return balance;
}
//Withdraw method
public void withdraw(double withdraw)
{
balance = balance - withdraw;
}
//Deposit method
public void deposit(double deposit)
{
balance = balance + deposit;
}
//Adding monthly interest to the balance
public void addInterest()
{
double x = ((interest/12) * balance);
balance = balance + x;
}
}
I get these errors:
--------------------Configuration: --------------------
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:43: error: variable amountWithdraw might not have been initialized
amountWithdraw += num;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:46: error: variable w might not have been initialized
w++;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:50: error: variable amountWithdraw might not have been initialized
money.withdraw(amountWithdraw);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:62: error: variable amountDeposit might not have been initialized
amountDeposit += num;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:65: error: variable d might not have been initialized
d++;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:69: error: variable amountDeposit might not have been initialized
money.deposit(amountDeposit);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:73: error: variable filenameOutput might not have been initialized
oFile=new PrintWriter (filenameOutput);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:75: error: variable w might not have been initialized
oFile.println("The total amount of withdrawls are: " + w);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:76: error: variable d might not have been initialized
oFile.println("The total amount of deposists are: " + d);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:37: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
iFile = new Scanner (wFile);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:55: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
iFile = new Scanner (dFile);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:73: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
oFile=new PrintWriter (filenameOutput);
^
12 errors
Process completed.
I'm not looking for handouts, this is my first post for help here but I know you guys wont solve this for me...I just need to learn how to do this properly. I just have no idea why the initialization is having a problem (all mentioned variables are initialized) and the files are located in the same folder.

I think you are confused about the difference between initialization and declaration. The variables that give errors are indeed declared, but they don't have an initial value.
Take a look at w++. This means: add 1 to w. But what is w? You didn't define that.
The same problem is true for d, amountWithdraw and amountDeposit
Also, new scanners with a file as input need a try-catch statement for a FileNotFoundException.
Finally, I think you meant filenameOutput="output.txt"; in stead of filenameInputW="output.txt";

--------------------Configuration: --------------------
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:43: error: variable amountWithdraw might not have been initialized
amountWithdraw += num;
Well, you declared variable amountWithdraw as double, but compilator don't know what is value of this variable and he can't add num. So after declaration you need to initialize amountWithdraw. It can be like this:
amountWithdraw = 0;
It's so simple.

From your code you write the following at the very top: double amountWithdraw; and that's it. This is not an initialization, but a declaration.
The same applies if your girlfriend starts talking about kids, right? If she declares "I want kids" it's not the same as if she "initializes" (gives birth to) a baby. Both might be equally stressful, but in different ways.
You need to either type double amountWithdraw = 0.0; or add the following before modifying the value: amountWithdraw = 0.0;. That will fix the first of your handful of problems.

Edit: For the wrongs...
You should be giving those variables values when you declare them. i.e. int w = 0 etc.
Dirty quick fix: As for the other exception-related errors, for simplicity you can just put public static void main(String[] args) throws FileNotFoundException to get things working in the interim.
Proper fix: Usually though, you should look to handle a FileNotFoundException in a catch block, as it's not good practice to rethrow exceptions willy-nilly.

Related

Void method in Java | BankAccount Class Constructor

I need to create a void method for withdrawals that accepts a double, along with setting a balance + the amount entered parsed as a double.
I have typed this so far: public void; I am unsure how to continue.
This is the whole code that I have:
// Create a class named BankAccount
public class BankAccount {
// Create a double named balance
double balance;
// Create a no-arg constructor named BankAccount
// Set balance to 0.0
public BankAccount()
{
balance = 0.0;
}
// Create a constructor named BankAccount that accepts a BankAccount object
public BankAccount(double initialBalance)
{
// Set balance to the balance of the BankAccount object
balance = initialBalance;
}
// Create a constructor named BankAccount that accepts a double
// Set balance to the user's entered double
public BankAccount(double userBalance)
{
balance = userBalance;
}
// Create a constructor named BankAccount that accepts a string
// Set balance to the user's entered string parsed as a double
public BankAccount(String[])
{
double balance = 0;
}
// Create a void method for deposits that accepts a double for the amount
// Set balance to balance + the amount entered
public void deposit(double depositAmount)
{
balance += double depositAmount;
}
// Create a void method for deposits that accepts a string for the amount
// Set balance to balance + the amount entered parsed as a double
public void deposit(String[])
{
balance += double depositAmount;
}
// Create a void method for withdrawals that accepts a double for the amount
// Set balance to balance - the amount entered
public void
(This is for an assignment. One of my classmates recommended this site to get some help and my teacher is pretty chill about looking for answers from different sites.)
Edit: I finished the code but am getting some errors.
Here are the errors I'm getting:
./BankAccount.java:32: error: <identifier> expected
public BankAccount(String[])
^
./BankAccount.java:24: error: constructor BankAccount(double) is already defined in class BankAccount
public BankAccount(double userBalance)
^
Main.java:19: error: cannot find symbol
account1 balance = 1200;
^
symbol: class account1
location: class Main
./BankAccount.java:69: error: cannot find symbol
balance = userBalance;
^
symbol: variable userBalance
location: class BankAccount
4 errors
If you want to create a method, you must have a return type. It should be after the access modifier and before the method name.
For clarifications, void is a return type that indicates that your method isn't required to return a data. (Implicitly, it just returns null)
From your instance, you can have the following method to add the value of the parameter depositAmount to the global variable balance:
public void deposit(double depositAmount) {
balance += depositAmount;
}
From your example, you don't need to declare the variable type (double) again because it was already declared on the parameter.
For your other requirement, you can have the following method to deposit an array of depositAmounts in String:
public void deposit(String [] depositAmounts) {
for (int i = 0; i < depositAmounts.length; i++) {
balance += Double.parseDouble(depositAmounts[i]);
}
}
To create a withdrawal method you can have the following method:
public void withdraw(double withdrawAmount) {
balance -= withdrawAmount;
}
Cheers.
You'd want to continue as follows:
public void withdraw(double amount) {
balance -= amount;
}
The method withdraw is of a void return type, which means it does not return anything. If you would like it to return a balance, you'd need to type double instead of void and add a return value (return balance;). It's not neccesary or needed of course, I'm just pointing out the distinction of what void means.
As it stands, the code above will take in one argument - amount to be withdrawn - and subtracts that amount from the balance.

Trouble with overtime program

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! :-)

Can't call data from second string

I have looked through some of the other questions asking about a similar issue, but I am trying to call the double 'thirdPrice' from calculationMethod() to main(). The purpose of this program is to request data in main(), pass some of the info to calculationMethod() and then return that data back to main() for final output. I am using DrJava, here is my code so far.
import java.util.Scanner; //Imports input device
public class CraftPricing
{
public static void main(String[] args)
{
Scanner inputDevice = new Scanner(System.in); //Sets up input device
String productName; //Used for naming product
double costMaterials, hoursWorked; //Gives variables decimal format
System.out.println("Enter the name of the product "); //Enter product name
productName = inputDevice.nextLine(); //Passes variable for calculation
System.out.println("Enter the cost of materials prior to discount "); //Enter cost of materials
costMaterials = inputDevice.nextDouble(); //Passes variable for calculation
System.out.println("Enter the number of hours worked "); //Enter hours worked
hoursWorked = inputDevice.nextDouble(); //Passes variable for calculation
System.out.printf("The cost of " + productName + " is %.2f\n" , thirdPrice);
//Output product name and cost
}
public static void calculationMethod() //Method used to calcualte price
{
double itemDiscount = 0.75; //Gives decimal format to variable
double payRate = 14.00; //Gives decimal format to variable
double shipHandle = 6.00; //Gives decimal format to variable
double firstPrice = payRate * 7; //Calculates fisr portion of equation
double secondPrice = 7 + firstPrice; //Calculates second portion of equation
final double thirdPrice = itemDiscount * secondPrice + shipHandle;
//Calculates final portion of equation
return thirdPrice; //Returns double to main() for output
}
}
The errors I receive when trying to compile are as follows:
2 errors found:
File: C:\Users\unkno\DrJava\Java\CraftPricing.java [line: 18]
Error: cannot find symbol
symbol: variable thirdPrice
location: class CraftPricing
File: C:\Users\unkno\DrJava\Java\CraftPricing.java [line: 28]
Error: incompatible types: unexpected return value
Why do you need a variable at all?
Call the method.
System.out.printf("The cost of %s is %.2f\n" , productName, calculationMethod());
Or learn about variable scope.
And also fix the return type.
public static double calculationMethod()

How do I fix a Java:26: error: No suitable constructor found

I'm pretty new to Java script writing and I'm trying to fix four errors I get when I compile my code. I'm so frustrated, what am I doing wrong?
The Errors are:
SavingsAccount.java:25: error: no suitable constructor found for BankAccount(String,double,double)
super(name, balance, interestRate);
^
constructor BankAccount.BankAccount(String,double) is not applicable
(actual and formal argument lists differ in length)
constructor BankAccount.BankAccount(String) is not applicable
(actual and formal argument lists differ in length)
SavingsAccount.java:29: error: cannot find symbol
Interest = balance * (interestRate / 12);
^
symbol: variable Interest
location: class SavingsAccount
SavingsAccount.java:29: error: cannot find symbol
Interest = balance * (interestRate / 12);
^
symbol: variable interestRate
location: class SavingsAccount
SavingsAccount.java:31: error: cannot find symbol
this.deposit(interest);
^
symbol: variable interest
location: class SavingsAccount
4 errors
My code:
import java.util.Scanner; // Needed for the Scanner class
import java.text.DecimalFormat; // Needed for 2 decimal place amounts
import java.util.logging.Level;
import java.util.logging.Logger;
class SavingsAccount extends BankAccount {
static {
BankAccount account; // To reference a BankAccount object
double balance, // The account's starting balance
interestRate; // The annual interest rate
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create an object for dollars and cents
DecimalFormat formatter = new DecimalFormat("#0.00");
// Get the starting balance.
// Get the annual interest rate.
interestRate = keyboard.nextDouble() * .001;
// post monthly interest by multiplying current balance
// by current interest rate divided by 12 and then adding
// result to balance by making deposit
}
public SavingsAccount(String name, double balance, double interestRate)
throws NegativeAmountException {
super(name, balance, interestRate);
}
public void postInterest() {
Interest = balance * (interestRate / 12);
try {
this.deposit(interest);
// and current account balance (use printStatement from
// the BankAccount superclass)
// following this also print current interest rate
} catch (Exception ex) {
Logger.getLogger(SavingsAccount.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
BankAccount.java (This one works with no errors):
class BankAccount {
public String name;
public double balance;
public BankAccount(String name, double balance) throws NegativeAmountException {
this.name = name;
this.balance = balance; // set name and balance
if (balance < 0) { // make sure balance is not negative
throw new NegativeAmountException("Can not create an account with a negative amount."); // throw exception if balance is negative
}
}
public BankAccount(String name) throws NegativeAmountException {
this(name, 0); // set name and use 0 balance
}
// update balance by adding deposit amount
// make sure deposit amount is not negative
// throw exception if deposit is negative
public void deposit(double amount) throws NegativeAmountException {
if (amount > 0) {
this.balance += amount;
}
else {
throw new NegativeAmountException("Deposit amount must not be negative");
}
}
// update balance by subtracting withdrawal amount
// throw exception if funds are not sufficient
// make sure withdrawal amount is not negative
// throw NegativeAmountException if amount is negative
// throw InsufficientFundsException if balance < amount
public void withdraw(double amount) throws InsufficientFundsException, NegativeAmountException {
if (amount > getBalance()) {
throw new InsufficientFundsException("You do not have sufficient funds for this operation.");
}
else if (amount < 0) {
throw new NegativeAmountException("Withdrawal amount must not be negative.");
}
else {
this.balance -= amount;
}
}
// return current balance
public double getBalance() {
return this.balance;
}
// print bank statement including customer name
// and current account balance
public void printStatement() {
System.out.println("Balance for " + this.name + ": " + getBalance());
}
}
You have 2 errors in code:
About first error Java compiler notes that in superclass BankAccount you haven't constructor with 3 variables (your call super(name, balance, interestRate); in SavingAccounts class. You should:
add corresponding constructor to BankAccount class or
use existent constructor from BankAccount class and keep interestRate as SavingAccounts class variable.
Second error makes 3 error by compiler opinion: in code Interest = balance * (interestRate / 12); you lost local variable. After fix it (seems that should be double interest = balance * (interestRate / 12);) you'll remove 3 errors.
There are multiple problems with your code.
You normally do not use a static block as you do. You may want to write a public static void main(String... args).
The actual problem with your code is the superclass-constructor call via super(...). BankAccount does not provide an accessible constructor with the specified signature (String, double, double). Either there is no such constructor or the constructor is not visible (see this for details).
For the other errors regarding Interest, please look at Pavel's answer.
Furthermore, there are some general accepted coding standards for Java, some can be found here. Please respect them.

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