Variable error and cannot convert to boolean error - java

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

Related

Looking for help on creating more efficient way on doing a lot of checks

Note: Not a duplicate of How do I compare strings in java as I am taking about going through some checks to determine if something is inheriting something something else
Is their a better and more efficient way to do this:
As you can see I am inputting 2 strings then checking them of on a list, as if current = three then it returns true for checking for one, two and three
NOTE: these values(one,two,three) are just placeholders for the example in my use their is no relation between them except that they have a different priority.
public boolean checker(String current, String check) {
if (check.equals("one")) {
if (current.equals("one") || current.equals("two")
|| current.equals("three")) {
return true;
}
}
if (check.equals("two")) {
if (current.equals("two") || current.equals("three")) {
return true;
}
}
if (check.equals("three")) {
if (current.equals("three")) {
return true;
}
}
return false;
}
Here are a few pointers
As Frisch mentioned in comments, use .equals rather than == for String comparison.
Use switch/case
switch (check) {
case "one":
if (current.equals("one")) return true;
case "two":
if (current.equals("two")) return true;
case "three":
if (current.equals("three")) return true;
}
Apart from that, there doesn't seem to be much to do.
Two things.
Don't check strings using equality. Use the .equals() method. You can call it off the string literal. So something like this. Calling it off the string literal is safe even with nulls, which is generally a good thing.
if ("one".equals(check))
You can take advantage of Java's short circuit operators && and ||
if ("one".equals(check)) {
if ("one".equals(current) || "two".equals(current) || "three".equals(current)) {
return true;
}
}
Can become
if ("one".equals(check) && ("one".equals(current) || "two".equals(current) || "three".equals(current))) {
return true;
}
Which will be evaluated from left to right. Since the "one".equals(check) is on the far most left, and is &&'ed with the rest of the statement, Java will bail out of the condition checking if "one".equals(check) is not true, and will not evaluate the rest of the statement.
Since you're just returning true or false, you can also take this a step further and reduce all of your if statements into a single one using De Morgan's laws (http://en.wikipedia.org/wiki/De_Morgan's_laws). Generally you state your boolean if statement in the way that is most natural to you, and then you start simplifying it by applying transformations that keep the logical if statement the same.
A good example of this is, stolen from the below link.
In the context of the main method's program body, suppose the following data is defined:
int score, min = 0, max = 20;
boolean bad, good;
Further suppose that a value is assigned to score, perhaps from a keyboard entry, and I would like to test, with a Boolean expression whether the score is a valid number or not. A good score is in the closed range [0 .. 20], which includes 0 and 20.
good = (score >= min && score <= max);
I would like to get the score from the keyboard in a do while loop, so that I can validate the entry. The logic in my control structure is to demand another entry for the score while the entry is bad. I have a definition of a good entry, and I will use definitions of operators and De Morgan's Law to help me write an expression that represents a bad entry.
good = (score >= min && score <= max); // original definition of good from the logic of my task
good = !(score < min) && !(score > max); // by definition, >= means ! < , <= means ! >
good = !(score < min || score > max); // by De Morgan's' Law
bad = !good ; // bad is not good
bad = !!(score < min || score > max); // substituting for good
bad = score < min || score > max; // double negation is dropped
http://fcmail.aisd.net/~JABEL/1DeMorgansLaw.htm
I would like to update you some thing.
1. We can apply switch cases only on primitive data types but not on objects. As string is object we can't use strings in case/switch statement.
I would like to suggest you to enums/maps in this case.
Please find the below sample programm how i implemented using maps.
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<String, Integer>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
String current = "one";
String check = "one";
if(map.get(check)<=map.get(current)){
System.out.println("Our condition is success");
}
}
Instead of multiple comparison this is better.
---Santhosh

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.

Converting double numerical value to text

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);
}
}

If-else block in nested for loops - Compiler claims I need a return statement

How do I make this work? It says that I need to add a return statement but I have one.
public boolean clockFactCheck(int a, int b){
for (int i = 0; i <= 276; i++){
for (int h = 0; h <= 55; h++){
if (a == i + 186 && b == h + 133){
return true;
} else {
return false;
}
}
}
}
The code provided may not reach one of the returns for any input a,b and that's what the compiler is complaining about.
Actually in your case the if-else will be reached with the very first iteration - unfortunately something which the compiler cannot deduce. Therefore, it goes the save way and issues this error.
Comment: Therefore, in your loop seems not to make much sense since it will not iterate at all but stop within the first iteration i==0 and h==0. Did you meant to code something like that?
You don't have a return statement after the for loop but even then h++ is dead code becaue it will never get past the first iteration.
Place the return statement outside the loop. (declare a boolean in your function, modify it and return it at the end)
My guess is that the compiler is not clever enough to figure out that there is no codepath around the loops.
If this is real code, simplify it to
return (a == 186 && b == 133);
If this is not the real code, there is probably another path that does not return (if you made an error pasting), or there really is a compiler bug or limitation. At one point, the halting problem bites you, and the code is too complex for the compiler to figure out.
In the latter case I would place a
throw new RuntimeException(
String.format("should never get here (a = %d, b = %d) !",a,b));
at the last statement.
That makes both the compiler happy and does not introduce an "undefined" return value for a case that should either never happen, or if it does, has not been thought of.
Oh yeah my bad, I'm sorry this was a stupid question it was 5am when I posted this. I figured out the answer to my problem. If you made the same stupid mistake as me here is the fix
public boolean clockFactCheck(int a, int b){
for (int i = 0; i <= 276; i++){
for (int h = 0; h <= 55; h++){
if (a == i + 186 && b == h + 133){
return true;
}
}
}
return false;
}
Java requires every path return a value. The compiler could not judge if the circulation will return a path. If your code is like this:
public boolean add(){
for(int i=0;i<100;i++)
if(i==5000)
return true;}
the function add will not return a value. Instead, an error will occur.

Java conditional statement/ initializing variable

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.

Categories