So I got this error in my program:
BankChargesWilson.java:55: error: variable checksCost might not have been initialized
System.out.println("Your total cost is " + money.format(checksCost) + ".");
^
1 error
But I don't understand why when I have the formatting object created and I initialized the checksCost variable earlier.
Heres the object + my definitions.
// Decimal Format Object
DecimalFormat money = new DecimalFormat("$##,###.##");
// Scanner Object for Input
Scanner keyboard = new Scanner (System.in);
// Variables
double baseFee = 10.00; // The base fee the bank requires for the account
double checkFee; // The fee for a check
int checksWritten; // The users inputted amount of checks written for the month
double checksCost; // The cost for the checks based on the amount written in the month
And heres my else-if statements where it's used, with the output and the spot thats causing an error.
if (checksWritten < 20)
{
checksCost = checksWritten * 0.10;
}
else if (checksWritten >= 20 && checksWritten <= 39)
{
checksCost = checksWritten * 0.08;
}
else if (checksWritten >= 40 && checksWritten <= 59)
{
checksCost = checksWritten * 0.06;
}
else if (checksWritten >= 60)
{
checksCost = checksWritten * 0.04;
}
System.out.println("You entered that you wrote " + checksWritten + " checks this month.");
System.out.println("Your total cost is " + money.format(checksCost) + ".");
I'm not sure why it's saying it's not initialized anymore.
Question though: Is the checksCost being seen in only the scope of my if-else-if loop? And if so, how come when it's defined further above?
Because the compiler doesn't analyze your code so deeply as you would imagine.
Although your if/else chain will execute a branch for sure according to its conditions, this outcome is not realized by the compiler which complains about the fact that you are missing an else condition.
You could solve the problem by initializing the variable or by letting last else if be a simple else (which wouldn't alter semantics in this specific case).
You need to provide a default initial value or you have to provide else block and provide your value there.
The reason is that, What happens all of your conditions failed to execute ??
When you provide a else block, then it is sure that always there is a chance to assign the value, either in if or in else
double checksCost;
if(){ //false
}
else if(){ //false
}
what is checksCost value now ??
Yes, your checksCost variable is only being see inside the block where it is initialized (in this case within the sections of the for loop).
The reason it can be seen inside the blocks of the if-else statement even though it has been declared above is because inner blocks can access code outside themselves but the reverse is not true.
You need to set an initial value for the checksCost variable. There could be a case where the value never gets set. There may be a situation where none of your conditional logic would be hit.
Java compiler requires that the variable must be initialized. At compile time, it doesn't check the logic of your code, so it thinks that there's a chance the variable will not be initialized if none of the "else if" match.
You need to initialize checkCost before the if/else part, or put an else { double = smth; } to end the if/else clause.
If checksWritten is equal to 0 what should checksCost equal? Initialize checksCost to that. Along the same lines you should probably initialize checksWritten to 0. Also don't leave off an else block ever because it leads to brittle code as you have just found out. So in this case just change the last else if to else.
Related
I have called 'setPrice()' mutator method from a class 'Holiday' which holds 'double' as a data type. However, when I add 'holiday.setPrice()', it says "method setPrice in Holiday class cannot be applied to the given types: double". I am confused to why that is.
public void checkOut(Member member, Holiday holiday){
if(member.getBalance() >= holiday.getPrice()){
System.out.println("Transaction complete");
System.out.println("You have been automatically logged off");
member.setLoginStatus(false);
if(checkHitDiscount() == true){
holiday.setPrice() = discount - holiday.getPrice() ;
System.out.println(" Good news! You're eligible for a discount!");
}else{
System.out.println("No discount available, try again next time");
}
} else {
System.out.println("You don't have suffiencient funds");
}
}
You are attempting to use the following line:
holiday.setPrice() = discount - holiday.getPrice();
This should probably be
holiday.setPrice(discount - holiday.getPrice());
instead. The inputs of a function go inside its parentheses.
EDIT: discount and holiday.getPrice() should also probably be reversed, based on their names.
EDIT2: What your existing code is trying to do is assign the value of discount - holiday.getPrice() to the double which is returned by a hypothetical holiday.setPrice() with no inputs. This is not allowed, because that is a value, not a variable (ie: a name referring to a spot in memory storing a value). It's a bit like trying to execute 5 = 3 + 4;.
I am writing a program where the application has text fields to enter dollar amounts.
There are methods that need to throw exceptions for items such as dollar amounts less than zero. when doing this I have check for exceptions like this:
if (Double.parseDouble(str) <= 0 || Double.parseDouble(str) > 10000)
throw new InvaildDepositAmount("Deposit Amount " + str);
else
totalBalance += amount;
My question is : Do I need to use the Double.parseDouble(str) every time I want to use this input, such in the InvalidDepositAmount class?
The simple answer is no. You can parse it once and use it as a variable later.
double depositAmount = Double.parseDouble(str);
if (depositAmount <= 0 || depositAmount > 10000)
throw new InvaildDepositAmount("Deposit Amount " + depositAmount);
else
totalBalance += depositAmount;
This is also more efficient because, what if the call to parseDouble were expensive (that is, it took a long time for it to get an answer)? Calling it once would be more efficient and easier to read in the long run.
You can just use a variable.
double x = 0;
try {
double x = Double.parseDouble(str);
} catch(Exception ex) {
throw new InvaildDepositAmount("Deposit Amount " + str)
}
if (x <= 0 || x > 10000) {
throw new InvaildDepositAmount("Deposit Amount " + str)
}
I think it makes to code readable, but I'm not sure if it makes it more efficient because the compiler or JVM could notice that and use that expression just once (and do exactly what i'm doing in the code :))
Looks like you have following cases here:
1. input field that should accept only double numbers
2. some functions which accept limited range of double numbers
Obviously you can cache entered value to avoid redundant invocation of Double.parseDouble. Also you should keep that cached value actual and update it if user changed the value in input field.
In case of exceptions related to limits in your functions you can show some popup, or update status line or whatever is suitable for your application. Or probably you want to limit input field about entered value and validate value after each change.
Currently this is my code, and I need to display " Please enter a valid choice" when the user don't pick A,B,C,D,E or F as their choices. The problem is if I put the statement " Please enter a valid...." on the "else" conditional, Java would ask me to initialized the variable ActivityFactor as there will not be one if the user don't select the correct choice. Anyone know how I can fix this? Or any idea how I should code a program to do such?
if((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("A"))
ActivityFactor = 1.0;
else if ((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("B"))
ActivityFactor = 1.3;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("C"))
ActivityFactor = 1.6;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("C"))
ActivityFactor = 1.5;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("D"))
ActivityFactor = 1.7;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("D"))
ActivityFactor = 1.6;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("E"))
ActivityFactor = 2.1;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("E"))
ActivityFactor = 1.9;
else if (inGender.equalsIgnoreCase("M") && inActivity.equalsIgnoreCase("F"))
ActivityFactor = 2.4;
else if (inGender.equalsIgnoreCase("F") && inActivity.equalsIgnoreCase("F"))
ActivityFactor = 2.2;
else
{
ActivityFactor = -1;
}
//After
if(ActivityFactor != -1){
tdee = (nBMR * ActivityFactor);
System.out.println(tdee);}
else
{ System.out.println("Please enter a valid choice");
}
If non of the conditions in the if statements is true, then you don't assign anything to ActivityFactor, and it is not initialized when used in the line double TDEE = (nBMR * ActivityFactor);.
Either initialize it before the code you've shown here, give it a default value in the last case, or loop until you get a valid value.
initialise ActivityFactor to an usual value before your conditional.
For example you may do this:
// knowing that it can never be -1
// so if that value remains, you know that user entered wrong letter
ActivityFactor = -1
// then the conditional begins
if((inGender.equalsIgnoreCase("M") ||(inGender.equalsIgnoreCase ("F"))) && inActivity.equalsIgnoreCase("A"))
...
// after conditional...
if(activityFactor != -1){
double TDEE = (nBMR * ActivityFactor);
}
By the way, I suggest you use 'activityFactor' instead of ActivityFactor.
Either initialize your variable before the loop, or place the whole loop inside a function and then do something like:
double TDEE = (nBMR * getActivityFactor());
Also, have a look at this : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
happy coding! ;)
You should do two things:
Enclose the logic in method
Throw an exception if argument do not match the method logic.
You can solve this problem throwing an exception that you will catch.
private double getTDEE (String inGender, String inActivity) {
//logic
else {
throw new IllegalArgumentException("Please enter a valid choice");
}
return (nBMR * ActivityFactor);
}
Exception tutorial
As you're already aware, the problem with your code is that execution continues regardless of whether the user has entered valid input. Due to this, much refactoring is due - I would also attempt to make the conditional statements a little bit prettier; but that's personal preference.
Possible solutions:
a) Use a loop - Then break out of the loop when the user has entered satisfactory input..
while( true ){
/* get input from the user */
/* run through validation checks...
and -break- out of the loop when they're satisfied */
}
/* do calculations here */
b) Use a function to abstract all this logic away.. (as Psyclops suggests)
Personally, I would use a combination of these approaches - have all of this logic extracted away in to a function which returns false when no valid input is entered, and then use a construct like while(! yourFunction() ) to simply loop through it until it's completed. You could using passing by reference to avoid having to use the return type for anything other than a boolean value.
I wouldnt initialise the variable before the loop! This just means the programme will continue to execute; however it wont have any appropriate data in there - which is potentially worse than the application just crashing.
I haven't exactly gifted you the answer in code - but hopefully it's a starting point to allow you to think about how to conceptually compose/design such a solution. That's generally the hardest part.. ;) Good luck.
So I’ve bolded were the errors are happening but I don’t understand why they are happening. It doesn’t make sense to me.
for(int i = 1; i < Array.getLength(purchases);i++)
{
System.out.print("\n");
System.out.print("Enter a price for item #"+i+": $");
double temp3=input.nextDouble();
double price=temp3;
if(price=>0) **<==it wont let me have both = and >**
{
total=total+price;
double temp1=total*100;
int temp2=(int)temp1;
total=temp2/100.0;
System.out.print("That was $"+price+". Your total is $"+total);
}
else(price==0) **<=="The left-hand side of an assignment must be a variable"**
{
}
}
if(price=>0)
This should be: -
if(price >= 0)
Note the order of > and =. > comes first.
And also: - else(price==0) should just be else, you don't need to add a condition in your else.
your greater than or equal to ordering is wrong.
if(price=>0)
should be
if(price>=0)
the correct ordering is to use >=
else(price==0)
should be
else if(price<0) //should be less than zero , because you are already checking if price is >=0 in your if.
or just else would suffice
nested if-else syntax:
if(somecond){
}
else if(somecond){
}
else{ // you don't mention any condition for else, as it would be the last condition.
}
In java, "greater than or equal to" is >=.
Also, for the second error, you should have "else if", not just "else."
this is my first programming course, and i want to make sure i am doing this problem correctly. if you could check over my work it would be greatly appreciated.
Write a method to compute and return the balance for a checking account, given the starting balance and an array of Check objects. You may assume that the Check class already exists and has a method to get the amount from a particular check object called: double getAmount()
The array is not full, and may have gaps in it – make sure you test to see if there is an object there before you try to access it! Make your code work for any length array!
The header for the method is provided for you:
public double computeBalance(double startingBalance, Check[] register) {
int i = 0; // i must be initialized and declared somewhere at least
double total = 0.0;
while ((i >= check.length) && check[i] != null) { // is >= correct? you do i++!
total = (total + getAmount(check[i])); // should you add/compute somewhere
// the given amounts
i++;
}
System.out.println(total);
}
Forget programming for a second. If I told you "Here's the starting balance in your account." and then handed you a bunch of checks and told you to compute the ending balance, how would you do it? Once you understand that, you can start to work on the programming problem.
Some questions:
Where are you tracking the account balance?
What will happen in your loop if one of the slots in register is empty (i.e. null)?
What is this check variable in your loop? Where is it being declared? Is check really what it should be called?
The function is declared as returning double. What are you returning?
Have you tried compiling your code? What happens?
I understand that you are asking for more than for the solution itself but there are obviously better people to guide you. You can use my example as a reference to what others are explaining to you.
public double computeBalance(double startingBalance, Check[] register) {
// let's start off from the starting balance
double total = startingBalance;
// go over all elements starting from 0
for (int i = 0; i < check.length; i++) {
// make sure you did not encounter null element
if (register[i] != null) {
// increase the total by the amount of the Check
total += register[i].getAmount();
}
}
// and finally return the resulting value
return total;
}
The execution will end when you reach a gap. Use an if-statement inside the loop for the null check instead.
If you could run your code through a compiler (which it sounds like you can't, or at least aren't being encouraged to), it would tell you that it has no idea what i, check, or getAmount are.
A method body that doesn't refer to the method parameters is generally missing something -- especially if the parameter declarations were given by your instructor.
Look again at your loop condition. What is the value of i going to be at the beginning?