Java conditional statement/ initializing variable - java

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.

Related

while loop inside for loop, confused?

Completely new to programming, and I was doing a project and I am confused on how I can make it work. Please help me
boolean answer1 = true;
for (int i=0;i<q.questionbank.length;++i)
{ q.Question = input(q.questionbank[i]);
while(answer1 == true)
{
if (q.Question.equals(a.correctans) || (q.Question.equals(a.impossibleans) || (q.Question.equals(a.wrongans))))
{
score = printquiz(answer,score,q.Question);
answer1 = false;
}
else
{
print("Not a Valid Answer, please try again\n");
}
}
}
return score;
Over here, I have a class called questionbank and quiz. The correctans/impossibleans/wrongans are part of the quiz data type. whereas the q.question is part of questionbank. I have some question on an array in the questionbank data type. I want to use for loop to go through the questions and if the user input the correct answer, there score goes up. It works for the first question but doesnt for the second question. usually when they answer correctly, I have another method printquiz that has decision statements to tell the user if their answer is correct or wrong, and assign them points. but its not even going to that method after the first iteration of the loop. I am confused on what is going on. Please help me
This is how I would have set it up. Assume the answer to be false until you get one. Then set it to true to exit the loop.
for (int i = 0; i < q.questionbank.length; ++i) {
q.Question = input(q.questionbank[i]);
answer1 = false;
while (!answer1) {
if (q.Question.equals(a.correctans) || (q.Question.equals(a.impossibleans) || (q.Question.equals(a.wrongans)))) {
score = printquiz(answer, score, q.Question);
answer1 = true;
} else {
print("Not a Valid Answer, please try again\n");
}
}
}
The second time doesn't work, because you set answer1 to false and never set it back to true again. So the while loop is not being entered anymore (= doesn't evaluate to true anymore) after the answer1 = false line of code in the if statement has been reached the first time.
To fix this, try to put answer1 = true inside the for loop, before the while loop.

JAVA Command line arguments to get info

I just have a small question which i cant understand , i hope i can get some help please .
I Want to write a program that get the info into my program using the command line, example (java xx 10 20). In my program i got something like this
int coffeeCups= Integer.parseInt(args[0]);
int coffeeShots= Integer.parseInt(args[1]);
if (args.length==0)
{
System.out.print ("No arguments..");
System.exit(0);
}
else if (args.length==1)
{System.out.println("not enough arg..");
System.exit(0);
}
else if (args.length>2)
{System.out.println("too many arg.");
System.exit(0);
}
else if (Integer.parseInt(args[0]<0) && Integer.oarseInt(args[1]<0)
{system.out.println("negative chain arg");
System.exit(0); }
else if (Integer.parseInt(args[0]<0) || Integer.oarseInt(args[1]<0)
{system.out.println("negative arg");
System.exit(0);}
I Want to enter only TWO POSITIVE INTEGERS INTO MY COMMAND LINE.. otherwise it should reject my inputs, but the thing is that sometime i came with en error like that (Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0) and sometimes my program runs without even entering any two integers in the COMMAND LINE...
I gotta finish my code as soon as possible, and i'de appreciate ur help
P.S. dont worry about the my identation as my program is not done yet
First of all, you may want to use a command-line-arguments parsing facility.
You're trying to access indices that do not exist:
// who said there is a first argument?
int coffeeCups = Integer.parseInt(args[0]);
// who said there is a second argument?
int coffeeShots = Integer.parseInt(args[1]);
You need to first check, then access:
// this is just like using sentinel value. If you're not familiar with
// shortend `if` see notes.
int coffeeCups = args.length > 1 ? Integer.parseInt(args[0]) : null;
int coffeeShots = args.length > 2 ? Integer.parseInt(args[1]) : null;
if (coffeeCups == null || coffeeShots == null){
throw new Exception("Not enough arguments");
}
if (args.length > 2){
throw new Exception("Too many arguments");
}
There is also the case in which the arguments are not Integers. You will get a NumberFormatException if that's the case...
Notes:
Short if notation (x ? y : z) is used to return y in case x is true, otherwise it returns z.

Validating a user's String type 'menu choice'

An assignment we were given recently had us building a basic, console-based, 'Tax Calculator', as it is something that got us to implement the things we'd learnt so far - variables, constants, loops etc.
One part of it had us present the user with a menu, where they would enter a letter - be it a,b,c,d or x - depending on what they wanted to do next.
That was no drama, as our assignment didn't ask for us to account for what happened if a user entered a choice not on the menu.
Now, for my own personal interest, I went back to it today, wanting to put some validation in there.
I defined the 'menuChoiceRule':
(menuChoice being a String)
boolean menuChoiceRule = (menuChoice.equalsIgnoreCase("A"))
|| (menuChoice.equalsIgnoreCase("B"))
|| (menuChoice.equalsIgnoreCase("C"))
|| (menuChoice.equalsIgnoreCase("D"))
|| (menuChoice.equalsIgnoreCase("X"));
And here is what should happen for as long as the rule is being broken: (The program should keep asking until it gets something that is in keeping with the rule, and then stop asking)
while (menuChoiceRule == false) {
System.out.print(menuChoiceString);
System.out.print("Enter Your Selection");
menuChoice = SCANNER.nextLine();
}
And what happens if the user is doing the right thing:
// As long as the user input is 'A','B','C' or 'D', they'll be able to
// keep doing stuff.
while (menuChoiceRule == true) {
*All the various menu options go here*
}
At the moment the while(menuChoiceRule == true) block (is that the right term?) works fine but while(menuChoiceRule == false) does not; Once the user inputs something that is in violation of the menuChoiceRule, the loop repeats endlessly no matter what is input (inputted?)
If someone could provide some insight as to why I'm having trouble here, it'd be much appreciated.
Regards,
AUS_Doug.
Looks like the boolean test is not being changed within the loop, place the code again at the bottom of the while loop.
Also, boolean tests do not need the ==, while(menuChoiceRule){ ... is the preferred coding style.
I would also consider creating a method to test for your rule:
private boolean testChoice(String menuChoice) {
return ((menuChoice.equalsIgnoreCase("A"))
|| (menuChoice.equalsIgnoreCase("B"))
|| (menuChoice.equalsIgnoreCase("C"))
|| (menuChoice.equalsIgnoreCase("D"))
|| (menuChoice.equalsIgnoreCase("X")));
}
This would give rise to the code:
boolean validChoice = false;
while (!validChoice) {
System.out.print(menuChoiceString);
System.out.print("Enter Your Selection");
menuChoice = SCANNER.nextLine();
validChoice = testChoice(menuChoice);
}

Why does Java say my variable is not initialized when it is?

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.

Variable error and cannot convert to boolean error

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."

Categories