Eclipse doesnt want to compile code in java - java

here is part of my code:
My eclipse is saying that i need to put a return statment. Why? I have it already, and this loop will always find at least one thread who is alive and return i, so it should end the function and return integer. Would be grateul for help.
public int SB(int dealer,int PL){ //
boolean NotFound = true;
int i;
if(dealer != PL-1)
i=dealer+1;
else
i=0;
while(NotFound){
if(TH[i].isAlive())
return i;
else{
if(i < PL-1)
i++;
else
i=0;}
}
}

You method is declared to return an int value. This means you are obligated to always return an int value, not just in your
if(TH[i].isAlive())
return i;
statement.
In your case, you return a value if a thread inside the TH array is alive.
What you can do is return an error value at the end of your method that will only happen if no threads inside TH are alive.
For example, you can add this statement at the end of your method:
return -1;
This part of the code will only be reached if your loop runs full iteration. Even if you know there will always be an alive thread and this part of the code will actually never be reached, you need to put it there to humor the compiler.
Also, your loop condition NotFound is never updated inside your loop. This means you have an infinite loop in case no threads inside TH are alive. You don't really need that variable at all. What you can do is change the loop condition to something like:
while(i < TH.length)
Or, as it seems the variable PL is the length of TH, you can put:
while(i < PL)
This would also protect you from an ArrayIndexOutOfBoundsException in case i goes beyond the length of TH

Your return is buried in an if statement. What if the if never becomes true? You must have a default return statement somewhere, perhaps as the bottom of your method or in an else block.

Related

error while returning a value from a for-if loop in java

I want to return a value from a for-if statement in java but unfortunately i am not able to do so.
I did try to return a value from inside a if statement from a for loop, but got an error
You have missing return statement because every branch of the code should return something, here in case the array is empty, then you don't do anything of the loop you'll have no return
Then you have put the else in the loop, so if the first number is not the one loop you for you return -1 meaning not found.
You need to wait the whole loop before being able to tell that you didn't find it
And that behaviour fix, solves the syntax issue too
public int search(int[] nums, int target){
for(int i=0; i<nums.length; i++){
if(nums[i] == target)
return i;
}
return -1;
}
The problem with your code (using you image here):
Even though you have the return inside the IF statement and the ELSE statement, they will only be reached only IF the code gets inside the FOR statement.
What would happen if you call your method with an empty nums array? if would skip the for statement and there is NOTHING to return for your method in this case, do you get it?
That's why you need a return outside the for/loop as well, meaning that: What your method wants to return if reaches this point?.
If it is a search, for example, you could return -1 outside the FOR/Loop and remove the ELSE statement from inside.
Don't wanna change to much your code, so you clearly see the difference, since you are clearly starting:
public int search(int[] nums, int target) {
int i;
int j;
int n = nums.length;
for (i=0;i<n;i++){
if (nums[i]==target) {
return (i);
}
}
return (-1);
}

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.

Compiler can't find variable in method with for,if/else return statement

I have a method, which keeps giving me compilation errors. At first I had a return statement for the if and else statements. I couldn't get it to work with 2 return statements, so I changed it into what I have now.
The error message now says that it can't find variable 'x'. I put the return statement inside the previous set of {}, and that still never worked. So I'm not sure if I have to completely redesign my method, or if this is a simple fix.
public static boolean equalN(int [] holdN){
for(int i=0;i<=holdN.length;i++){
int k=1;
boolean x;
if(holdN[i]==holdN[k]){
k++;
x=true;
}
else{
x=false;
}
}
return x;
}
The reason you cannot return x at the end of the method is that it is defined inside the loop, so its scope ends before you want to return it.
The same applies to variable k; good news is that you do not need either one of them.
At first I had a return statement for the if and else statements.
You can make it work with two return statements:
First return statement should be inside the if: once you detect the item that your loop is looking for, return true
Second return statement is at the end of the method, after the end of the loop. The only way to reach that point is for the loop to never return from the middle, which means that no item has been found. Hence, you return false.
Variable scoping is your problem here:
for(int i=0;i<=holdN.length;i++){
...
boolean x;
// x exists and is valid here
...
}
// but x doesn't exist here
return x; // this will fail compilation
}
To solve your compilation problem, you should move the declaration of x above the for loop.
boolean x;
for(int i=0;i<=holdN.length;i++){
...
}
return x;
}
For further explanation, see this SO question about variable scoping.

Java: infinite loop after an if inside a loop

So I have a loop that is wrapped around a loop and an if statement. When running the program however, it gets out of the inner loop (as planned) and then it fails the if statement (also as planned), resorting to the else statement which is a simple print.
What I /wanted/ to happen was have it then (in the case the if fails), restart to the original inner loop--hence the outer loop. But instead, after it fails the if statement, it begins to loop "phrase2" over and over.
Here is the simplified code:
int x = 1;
int y = 1;
int i = 0;
while(i == 0)
{
while(<condition that is false>)
{
System.out.println("phrase1");
a = input.nextInt();
b = input.nextInt();
}
if(<condition that is false>)
{
i = 1;
}
else
{
System.out.println("phrase2");
}
}
Thanks for your help regardless!
EDIT:
For the sake of emphasis...
What happens:
Infinite loop spewing "phrase2".
What I wanted:
After the else is executed, I wanted to be brought into the inner loop again.
Whatever condition you're using in the inner loop, just make sure it's true.
else
{
System.out.println("phrase2");
// SET THIS TO TRUE: <condition that is false>
}
This way, the inner loop will trigger again.
Your control never enters the below if statement
if(<condition that is false>)
{
i = 1;
}
You might need to adjust your conditions so that it comes into the above if block. Introduce a System.out.println inside if statement to debug
It looks like you have some code that you probably want to run once, unless something went wrong, and then you want to go back and retry. The idiom I usually use for that looks like
boolean needToRetry;
do {
needToRetry = false;
// do whatever
if (somethingWentWrong) {
needToRetry = true;
// set this at any point where you find you will need to go back
}
} while (needToRetry);
The important thing is that you need to reset your flag (needToRetry) at the beginning of the loop, each time. (P.S. There are other ways to do this using break or continue, although I personally don't like using continue.)

Java: perform for statement until given variable has reached a certain value?

I want to have a for statement that repeats until a given int reaches a certain value.
For example...
for (int variable = 0; variable < other_variable; variable++) {
The problem with this is that the for statement will never end. It will continue to repeat endlessly. What have I done wrong?
This is my code...
boolean itemexist_check = false;
do {
int i2 = m_area.m_items.size();
for (int i = 0; i < i2; i++) {
String s2 = m_area.m_items.get(i).returnName();
System.out.println("Checking...");
if (s2.contains(s)) {
System.out.println("You take the " + s2 + ".");
itemexist_check = true;
player.addItem(m_area.m_items.get(i));
m_area.m_items.remove(i);
}
else {
//do nothing, repeat loop
}
}
}
while (itemexist_check == false);
In this code, m_area.m_items.size() would return 1, so i2 would be 1.
There are several possibilities:
you change variable inside the body of the loop;
you change other_variable inside the body of the loop;
other_variable is set to a large value, in which case the loop might take a long time to terminate;
your code never completes a certain iteration of the loop, for example:
it's getting stuck inside a nested loop as suggested by #Eng.Fouad in the comments, or
it's waiting for a lock, or
it's blocking inside an I/O call that never completes (or takes a long time to complete) etc.
Without knowing the typical value of other_variable and seeing the body of the loop it's anyone's guess.
On a side note,
String s2 = m_area.m_items.get(i).returnName();
is going to cause an exception if invoked in a subsequent or later repetition after
m_area.m_items.remove(i);
is invoked, because every time m_area.m_items.remove(i) is invoked, the list/array loses an item and its size reduces, which is never reflected in the iteration boundary check.
Surely it is the do/while loop that isn't terminating? That for loop cannot possibly run forever.
You should try a
do {
}while(condition is true)
loop. However that said, you have to implement checks assuming that there will be runaway data or conditions resulting in an infinite loop. Just my 2 cents

Categories

Resources