multiple if statements without else - java

I don't understand why I get a compile error. In my view, this method first evaluates whether n is > 0. When this is the case, then "good" will be assigned to the String object local. However, if this is not the case, then it will not do anything. Next, the method enters another decision construct. This time, it evaluates whether n <= 0. If so, it will assign "bad" to the String object.
In any of both cases, local should be initialized. However, I get a compile error, and the compiler says it may not be initialized. I do not understand where this is coming from.
Note that I know how to correct the second if by replacing it with else and removing the boolean condition. I just don't understand why in a syntax sense this is incorrect.
public class Donkey{
String s1 = "green";
public void generateReport(int n){
String local;
if(n > 0)
local = "good";
if(n <= 0)
local = "bad";
System.out.println(local);
}

The compiler has no way to 'know' that you've handled all the cases with your if statements.
Consider this example (note that the second if is just less than):
String local;
if(n > 0)
local = "good";
if(n < 0)
local = "bad";
If n = 0, then local will not get defined.
The compiler doesn't test your if statements to see if they handle all the cases while compiling.
Changing it to if/else will fix the error as you mentioned. You can also initialize the variable as other users have pointed out.

The problem is that if n is not greater than 0 and is not less or equal than 0 the var local is not initialized. So that is what the compiler is telling you.
You can solve this by initializing the local var with something.
String local = "";
The problem is solved when you use else because for the compiler there can be only 2 possible states, the one if the condition is true and the other if is not, there is no possible third state because the else contemplates all.

Related

Cannot come up with why does my Java code loop infinitely

I tried to do this LeetCode daily challenge but I've found out that my code loops infinitely.
I looked through it multiple times, but I cannot find where the problem is. If anyone could spot it, please answer.
public int longestValidParentheses(String s) {
int count, highestOne = 0, index = 0;
boolean isSevered = false;
boolean theEnd = false;
while(!theEnd) {
count = 0;
while(!isSevered) {
if(index<s.length()-2) {
if(s.charAt(index) == '(' & s.charAt(index++) == ')') {count = count + 2;index = index+2;}
else {isSevered = true;}}
else theEnd=true;isSevered=true;
}
highestOne = count;
}
return highestOne;
}
I have 2 suggestions for you:
Use indentation and do not write if/else on the same line as the code associated with them
Always, ALWAYS use bracelets, even if you have only a single command. I think one of the wrongs java did is letting the programmers the free not to use bracelets if there is just a single command after it. It confusing.
So you have 2 mistakes here that make your code run for infinity:
isSevered will always be true after one loop exactly, as you change it to true no matter what happens as it is outside the if else statements, hence the reason I wrote the 2 advices above.
You never changing isSeveres or theEnd at the outside loop. Meaning that if isSevers is true and theEnd is false, you will never enter the internal while and will never exit the outside while.
The two of those combined means that if the condition that make theEnd be initialized with true won't happen at the first run, you will be stuck with infinity loop.

Java unexpected type Error Required Variable Found Value

public boolean replaceEventAt(String eventStr, int position){
boolean answer = false;
if((position > 0) && (position <= events.size())){
events.get(position - 1) = eventStr;
answer = true;
}
return answer;
}
Error on fifth line where Java complains that position is a value not a variable please help
An assignment operates between what is known as an lvalue and an rvalue.
lvalue stands for left-hand-side-value.
rvalue stands for right-hand-side-value.
The rvalue can be many things, like a variable, a constant, a function call expression, etc, but the left side must be assignable, so it cannot be a constant or a function call.
In your case, your rvalue is a function invocation; that won't work. The compiler error message is saying exactly that.
If we knew what you are trying to do we could perhaps explain more, but it is unclear from the code that you posted that it is that you want to accomplish. Perhaps events is some collection, and you want to set the element at position position - 1 to eventStr, in this case you would probably want events.set( position - 1, eventStr );
Left hand side must be a variable (ie we should be able to assign a value to it ). But in your case it is performing a get operation So it is throwing an Error
As you are trying to replace using index I assume events is object of List interface.
In this case below code should work as per your requirement.
public boolean replaceEventAt(String eventStr, int position){
boolean answer = false;
if((position > 0) && (position <= events.size())){
events.set(position - 1, eventStr);
answer = true;
}
return answer;
}

Throw Expected After This Token Error

When I run my code, it gives me an error that says, "Syntax error on token "{", throw expected after this token." The error is on line 7's code.
class WhileLoopTest {
public static void main(String[] args){
apple = 0;
while (apple = 0) {
(int)(Math.random( )*(60) + 5);
return;
}
}
}
on the line while (apple = 0) you are setting the variable instead of declaring it. The while loop expects that you pass it a boolean. You are probably trying to use the comparison equals ==. The full line should read while (apple == 0).
First , you need to define a type for your variable apple because Java is statically type
apple = 0;
Read more About Statically typed vs Dynamically typed
change to
int apple = 0;
Second, (int)(Math.random( )*(60) + 5); is not statement so you need to either print the value or return it
Third, while (apple = 0) { is wrong because compiler looking for Boolean expression
while(Boolean_expression)
{
//Statements
}
change to while (apple == 0 ) {
You need to add an extra equals sign to the condition within the while statement (at the moment you are assigning the value of 0 to apple, instead of texting if it is equal), so it looks like this
while(apple == 0){
Pleas note that the while loop has no function at all, since you are returning within the loop. This will stop your program execution as you are returning from the main method. The computation of a random number doesn't serve a purpose here as you aren't assigning a variable to it or printing it.
Also, you are not defining a type for the apple variable. Try making it of type int.
int apple = 0;
I suggest that you look up some tutorials on java as you seem to misunderstand several concepts within the language.

Eclipse warning: Cannot be null?

I'm getting what I think is a spurious warning from Eclipse on the following code, used to count the number of times a given element appears in a binary tree:
public int count(E item)
{
int count = 0;
Node crnt = root;
//First seek the item in the tree
while (crnt != null)
{
int compare = crnt.data.compareTo(item);
if (compare > 0)
crnt = crnt.right;
else if (compare < 0)
crnt = crnt.left;
else
{
//Shortcut if not allowing duplicate entries
if (!allowDuplicates)
return 1;
count++;
//Duplicates are always stored to the right
while (crnt != null) // <--Warning appears here
{
crnt = crnt.right;
if (crnt.data.compareTo(item) == 0)
count++;
else
break;
}
}
}
return count;
}
(I could show you the Node class, but it's nothing surprising. Just an `E for the data and two Node pointers for left and right children.)
Am I missing something or is this a bug in Eclipse? Because it seems like it's perfectly possible, and in fact expected for crnt to be possibly null in this case, once it runs out of right children. Granted it won't be null the first time it hits this loop, but usually the IDE is smart enough to realize when the value of the variable changes within the loop. Not this time, however. Eclipse is suggesting I put a #SuppressWarnings("null") on this, or I could go into the settings and turn off this warning altogether, but I don't think it should be necessary, and I hate suppressing or ignoring warnings where they might be useful.
crnt will still be different from null because it is in the else clause of the if-elseif-else statement that might change crnt. Its value will never have changed when it hits the second while statement.
It's doing exactly as it should: telling you that the value of crnt will never be null when that code hits and that the additional check in the while unnecessary is.
Per avice by David Wallace: there is no possibility that the inner loop will be null because the crnt object is already accessed prior to that by the line int compare = crnt.data.compareTo(item);, essentially forming a prerequisite that crnt must not be null.

increment a number in java until it gets to 100 than decrement down to 0 continously

I'm making a game where there is a goalie. i want him to move back and forth forever. i have an int called goalieposx (goalie position on the x axis) and i want this is go up by 1 until it hits 200, then go down by one till its back a 0 and repeat. I've tried the folllowing
//this bit isnt in the method, its outside as global varibale
boolean forward=true
//this bit is in a method which is continiouly called nonstop
if (goalieposx<200){
forward=true;
}
else if (goalieposx>200){
forward=false;
}
System.out.println(forward);
if(forward=true){
goalieposx++;
System.out.println("forward");
}
else if (forward=false){
goalieposx--;
System.out.println("backwards");
}
}
this method is called continously. It prints true until it gets to 200, then it prints false. However, it always prints forward, never backward. So conclusion is: the boolean changes as expected but the first if is always called, it seems to ignore the condition
ive also tried this
if(forward = true){
if(goalieposx==200){
forward=false;
}
else{
goalieposx++;}
}
else{
if(goalieposx==0){
forward=true;
}
else{
goalieposx--;}
System.out.println(goalieposx);
}
but this doesnt work either, it prints 1 then 2 etc upto 200 then prints 200 forever. Anyone know how i can solve this? is an if statement the wrong idea altogether?
This is why you should never do comparison for boolean types in if, while, for, whatever. You have just done the assignment in your if statement:
if(forward=true)
the above if statement will always evaluate to true. The problem with this is, this compiles successfully in Java, as syntax wise it's alright. Compiler just checks the type of expression in if evaluates to boolean or not. And it does, so it's ok with it.
You need to do the comparison:
if(forward==true)
.. but as I said, you should not do comparison for boolean types. So, simply doing this:
if(forward)
would be enough.
You also don't need those else if in both the conditions. Just an else will work fine. Well, I don't understand the use of boolean variable at all. It seems like you don't need it. You can change your code to:
if (goalieposx<200){
// forward=true;
goalieposx++;
System.out.println("forward");
}
else {
// forward=false;
goalieposx--;
System.out.println("backwards");
}
What you were previously doing is, setting a boolean variable, based on a condition, and using that boolean variable as condition to execute another if-else block. Well, whatever you are executing in the 2nd if-else block, can simply be moved in the original if-else block, without taking the help of the middle-actor boolean variable.
if(forward=true) does not do what you thing it does.
In java = is the assignment operator and == is the comparison operator. What you are doing with that statement is saying "if assign forward to true" which will set forward to true and always return true.
What you mean to say is if(forward) and if(!forward).
In fact you don't need the else if just an else as if the boolean is not true it must be false.
A better way to do it is to get it to move to the left by adding a minus number, and to the right by adding a positive number. Here's an example of doing this with a loop:
for(int i = -10; i < 100; i++) {
xPosition += i;
}
This would add -10 then -9 etc. to the position.
In your if statements, you need to put two equal signs to check for equality.
if (forward == true){
// execute code
}
EDIT 1:
if (forward)
would be much simpler.
First let's examine what you have already written:
if (goalieposx<200){
forward=true;
}
else if (goalieposx>200){
forward=false;
}
The problem with this code being first is that it while it might set the direction to false once 'goalieposx' has reached 201, in the next call, it will set the direction back to true.
Instead, try using this clever alternative:
//This goes before the infinite loop method
counter = 0;
//Then in the infinite loop method
counter++;
if(counter > 100) {
counter = -100;
}
goalieposx = 100 + counter; //(this shifts counter from
// between -100 and 100 to 0 and 200)
The problem is you are setting the direction based on the value of the integer, instead of whether a condition has previously been met. Try this:
//this bit is in a method which is continiouly called nonstop
if (forward && (goalieposx>200)){
forward=false;
}
System.out.println(forward);
if(forward=true){
goalieposx++;
System.out.println("forward");
}
else if (forward=false){
goalieposx--;
System.out.println("backwards");
}
}

Categories

Resources