For loop not executing at all? - java

So I have a program that deals with bytes. Everything works, except one part. A for loop doesn't execute at all.
This is the code...complex it is.
public int getID(int slot){
int slots = 0;
for(int a=0;a<b.length;a++){
if(correctslot){ //condition not shown.
if(slots==slot){
System.out.println("found pair");
for(int i=a;i<37;i++){
System.out.println("executing loop");
if(isID){ //condition not shown.
System.out.println("returning location");
return i+1;
}
}
}
slots++;
}
}
return 0;
}
If the program found a matching slot, it prints found pair. If it was executing the loop it prints executing loop, but that's the part that doesn't do anything at all. It prints the first string found pair but not the second executing loop. What did I do wrong?

Debug a . I think a >= 37 by the time either correctSlot && slots == slot .

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

How to exit a for loop if the if loop inside condition is met

I'm trying to create a method which allows you to choose which index in an array of test scores. It will check what the score is and return a grade for that score. In my getGrade method no matter what the score is it returns "NG".
private double[] scores = new double[3];
private static int[]boundaryVals={80,72,64,60,56,52,48,40,35,30,1,0};
private static String[]grades={"A1","A2","B1","B2","B3","C1","C2","C3","D1","D2","F","NG"};
public String getGrade(int i) {
String grade = "";
for(int x=0;x<boundaryVals.length;x++) {
if(boundaryVals[x] <= i) {
grade = grades[x];
}
}
return grade;
}
Just change the loop exit condition to terminate when a grade has been assigned.
public String getGrade(int i) {
String grade = "";
for(int x=0; x<boundaryVals.length && !grade.equals(""); x++) {
if (boundaryVals[x] <= i) {
grade = grades[x];
}
}
return grade;
}
This is better-structured since it has the loop termination condition in one place, rather than spreading it out by use of "break".
As usual, this is not a hard and fast rule. For more complicated cases, "break" is clearer. It's a matter of taste.
The 'return' from mid-loop, as suggested in comments, is not a bad solution in this particular case either. But I think it's worth pointing out that loop conditions are not limited to simple counting from 0 to N.
Because in the end 0 always smaller/equals to i, so even if 80 is less than i, finally i will de "NG";
Try add the keywords break; after grade = grades[x]; to stop the loop when the condition is true.
break is the keyword you're looking for.
As soon as the break statement is encountered inside a loop, the loop is terminated and it resumes with the next statement.
In your code the loop is never terminated until it gets to the last item in your array, which is 0. And 0 is always smaller than or equal to i. ;)

Why do I need to use count -=1 in the following code?

When creating the following function, in order to get a correct answer I have to add "count-=1" line, otherwise the answer gets skewed by 1.
public int countCTG(String dna) {
int count = 0;
int firstOccurrence = dna.indexOf("CTG");
if (firstOccurrence != -1) {
count +=1;
while (dna.indexOf("CTG", firstOccurrence) != -1 && firstOccurrence != -1) {
count +=1;
firstOccurrence = dna.indexOf("CTG", firstOccurrence+3);
}
count -=1;
}
else {
count = 0;
}
return count;
}
I managed to get this function working, however could you please help me understand the logic behind it? The count variable was initialized originally to 0 and if a string,for example, contains one instance of "CTG" it will be already counted in by "count +=1" line. Wouldn't count -=1 reset this variable back to 0?
You need the -1 because of the +1 before the loop: the first iteration of the while loop counts the already-found occurrence again.
An easier solution is like so:
int count = 0;
int skip = "CTG".length();
int current = -skip;
while ((current = dna.indexOf("CTG", current + skip)) >= 0) {
++count;
}
return count;
Because you're not updating firstOccurrence after your first search -- i.e. you're searching twice from the start (.indexOf("CTG")) before starting to search from the previous result (.indexOf("CTG", prevResultIndex + 3)).
Also note that:
you don't have to search once before the while loop
the else clause is redundant
you're calling .indexOf twice as many times as you actually need
the firstOccurrence+3 is a liability, you'll forget to update the offset when the string changes and it will be hard to track down. Store the searched-for string in one place, and compute its length instead of hardcoding it.
EDIT: Well #AndyTurner rewrote it for you, but try to see how each one of the listed points come into reaching that result

delete array [] elements

I am working on some data structures - after searching for an element, I am attempting to delete that element - but throws
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at SearchArray.deleteElements(SearchArray.java:68)
at SearchArrayDemo.main(SearchArrayDemo.java:25)
this is my method
void deleteElements(int value)
{
int j,k;
for (j=0;j<setArray.length;j++)
if ( value == setArray[j])
break;
if
(setArray[j] == setArray.length)
System.out.print("no item found");
else
{
for( k=j;k<setArray.length;k++)
`setArray[k]=setArray[k+1];`
k=setArray.length-1;
setArray[j]=0;
System.out.println("item deleted");
}`
and main method used to call that functions deleteElements
sa.deleteElements(5);
I did not include all the code for conciseness, this is the line where code breaks
setArray[k]=setArray[k+1];
please let me know if remaining code is required. thanks all for your help.
The problem here is that your loop end condition is
k<setArray.length
, but then you use
setArray[k+1]
Change the condition to
k < setArray.length - 1
for( k=j;k<setArray.length;k++)
setArray[k]=setArray[k+1]; \\ K+1 (invalid index when k = setArray.length-1
In your code, this will fail for the last element. Hence you get the exception
In an Array last index will be Array.length-1. In your case for the last element the code fails because k=Array.length-1 (last index) and k+1 = Array.length (which does not exist). Hence it throws out of bounds exception.
Your first for loop has some dead-code:
if(setArray[j] == setArray.length)
System.out.print("no item found");
This condition will never be reached in your loop for (j=0;j<setArray.length;j++)
if u want to delete the element in array 4
class arrayserch{
public int value(){
int[] arr={1,2,3,4,5,6;
int i=0;
for(int a:arr){
if(a==4){
return i;
}
else
i++;
}
return=-1;
}
}
class example{
public static void main(string arags[]){
arrsearch as=new arrrsearch();
int i=as.value();
if(i!=-1){
arr.length--;
for(int j=i;j<arr.length;j++)
{
arr[j]=arr[i++];
}
}
}
this may solve ur problem
Problem is this snippet:
for( k=j;k<setArray.length;k++)
setArray[k]=setArray[k+1];
When k == setArray.length - 1, setArray[k+1] goes beyond setArray boundaries
i dont't know your code
but line
setArray[k]=setArray[k+1];
it's out boundaries array

Difference between Return and Break statements

How does a return statement differ from break statement?.
If I have to exit an if condition, which one should I prefer, return or break?
break is used to exit (escape) the for-loop, while-loop, switch-statement that you are currently executing.
return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).
So to answer your question (as others have noted in comments and answers) you cannot use either break nor return to escape an if-else-statement per se. They are used to escape other scopes.
Consider the following example. The value of x inside the while-loop will determine if the code below the loop will be executed or not:
void f()
{
int x = -1;
while(true)
{
if(x == 0)
break; // escape while() and jump to execute code after the the loop
else if(x == 1)
return; // will end the function f() immediately,
// no further code inside this method will be executed.
do stuff and eventually set variable x to either 0 or 1
...
}
code that will be executed on break (but not with return).
....
}
break is used when you want to exit from the loop, while return is used to go back to the step where it was called or to stop further execution.
No offence, but none of the other answers (so far) has it quite right.
break is used to immediately terminate a for loop, a while loop or a switch statement. You can not break from an if block.
return is used the terminate a method (and possibly return a value).
A return within any loop or block will of course also immediately terminate that loop/block.
You won't be able to exit only from an if condition using either return or break.
return is used when you need to return from a method after its execution is finished when you don't want to execute the rest of the method code. So if you use return, then you will not only return from your if condition, but also from the whole method.
Consider the following method:
public void myMethod()
{
int i = 10;
if(i==10)
return;
System.out.println("This will never be printed");
}
Here, using return causes to stop the execution of the whole method after line 3 and execution goes back to its caller.
break is used to break out from a loop or a switch statement. Consider this example -
int i;
for(int j=0; j<10; j++)
{
for(i=0; i<10; i++)
{
if(i==0)
break; // This break will cause the loop (innermost) to stop just after one iteration;
}
if(j==0)
break; // and then this break will cause the outermost loop to stop.
}
switch(i)
{
case 0: break; // This break will cause execution to skip executing the second case statement
case 1: System.out.println("This will also never be printed");
}
This type of break statement is known as unlabeled break statement. There is another form of break, which is called labeled break. Consider this example -
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++)
{
for (j = 0; j < arrayOfInts[i].length; j++)
{
if (arrayOfInts[i][j] == searchfor)
{
foundIt = true;
break search;
}
}
}
This example uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search").
You can learn more abour break and return statements from JavaDoc.
Break statement will break the whole loop and execute the code after loop and Return will not execute the code after that return statement and execute the loop with next increment.
Break
for(int i=0;i<5;i++){
print(i)
if(i==2)
{
break;
}
}
output: 0 1
return
for(int i=0;i<5;i++)
{
print(i)
if(i==2)
{
return;
}
}
output: 0 1 3 4
break:- These transfer statement bypass the correct flow of execution to outside
of the current loop by skipping on the remaining iteration
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
break;
}
System.out.println(i);
}
}
output will be
0
1
2
3
4
Continue :-These transfer Statement will bypass the flow of execution to starting point of the loop inorder to continue with next iteration by skipping all the remaining instructions .
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
continue;
}
System.out.println(i);
}
}
output will be:
0
1
2
3
4
6
7
8
9
return :-
At any time in a method the return statement can be
used to cause execution to branch back to the caller of the method.
Thus, the return statement immediately terminates the method in which
it is executed. The following example illustrates this point. Here,
return causes execution to return to the Java run-time system,
since it is the run-time system that calls main( ).
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
return;
}
System.out.println(i)
}
}
output will be :
0
1
2
3
4
You use break to break out of a loop or a switch statement.
You use return in a function to return a value. Return statement ends the function and returns control to where the function was called.
break breaks the current loop and continues, while return it will break the current method and continues from where you called that method
Break will only stop the loop while return inside a loop will stop the loop and return from the function.
Return will exit from the method, as others have already pointed out. If you need to skip just over some part of the method, you can use break, even without a loop:
label: if (some condition) {
// some stuff...
if (some other condition) break label;
// more stuff...
}
Note, that this is usually not good style, though useful sometimes.
How does a return statement differ from break statement?.
Return statement exits current method execution and returns value to calling method.
Break is used to exit from any loop.
If I have to exit an if condition, which one should I prefer, return or break?
To exit from method execution use return.
to exit from any loop you can use either break or return based on your requirement.
break just breaks the loop & return gets control back to the caller method.
In this code i is iterated till 3 then the loop ends;
int function (void)
{
for (int i=0; i<5; i++)
{
if (i == 3)
{
break;
}
}
}
In this code i is iterated till 3 but with an output;
int function (void)
{
for (int i=0; i<5; i++)
{
if (i == 3)
{
return i;
}
}
}
If you want to exit from a simple if else statement but still stays within a particular context (not by returning to the calling context), you can just set the block condition to false:
if(condition){
//do stuff
if(something happens)
condition = false;
}
This will guarantee that there is no further execution, the way I think you want it..You can only use break in a loop or switch case

Categories

Resources