In the following if statement from a loop in my code, if the given oldsalary[i] doesn't meet these guidelines, I want to restore the previous numerical value of oldsalary[i] to "Error". However I want it to stay as oldsalary[i] since I will be displaying all the oldsalary[i] later in my code.
So basically when all the oldsalary[i] are displayed in another loop, I want to be able to see "Error" so it's know that something was wrong with that value.
I know the way I have it is completely wrong, I just put it like this to make sense. Sorry if it doesn't make any sense.
if(oldsalary[i] < 25000 || oldsalary[i] > 1000000){
JOptionPane.showMessageDialog(null, userinput[i]+"'s salary is not within
necessary limit.\n Must be between $25,000 and $1,000,000. \n If salary is
correct, empolyee is not eligible for a salary increase.");
double oldsalary[i] = "Error";
}
You can't store both the numerical value and an error indicator in a single double value.
Your best bet is to wrap the salary as an object that contains both the salary value and a boolean that indicates the error condition:
class Salary {
private double value;
private boolean error = false;
... constructor, getters and setters
}
And update your code to use the object instead. I.e.
if(oldsalary[i].getValue() < 25000 || oldsalary[i].getValue() > 1000000) {
oldsalary[i].setError(true);
...
}
So later you can do
if (oldsalary[i].isError()) {
// display error message
}
You can use an extra List that stores the indices that are no pass your requirement test.
List<Integer> invalidIndices = new ArrayList<>();
for (...){
if(oldsalary[i] < 25000 || oldsalary[i] > 1000000){
JOptionPane.showMessageDialog(null, userinput[i]+"'s salary is not within
necessary limit.\n Must be between $25,000 and $1,000,000. \n If salary is
correct, empolyee is not eligible for a salary increase.");
invalidIndices.add(i);
}
}
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?