0

breaking out of loops

1. To break out of a loop we use the "break" keyword. 2. Suppose i want some lines code not to run because the task is completed after a certain line. What keyword should i use. for example in the below code i already found what i want in inside the second if statement. so to save time i don't want i don't want any line after the second if statement to run/execute. how should i accomplish this. i tried to use the break keyword but it throws an error. public class JumpSearch{ public static void main(String[] args){ int[] arr = {2,3,4,5,6,7,8,9}; int x = 2; int rightindex = 0; int prevrightindex = 0; int jump = (int)Math.sqrt(arr.length); if(arr.length == 0){ System.out.println("The array is empty."); } if(arr[rightindex] == x){ System.out.println("The element(x) is found in the index."); } while(rightindex < arr.length){ rightindex = Math.min(arr.length-1, jump+rightindex); if(x<=arr[rightindex]){ break; } prevrightindex = rightindex; } if(rightindex>=arr.length-1 && x>arr[rightindex]){ System.out.println("The element(x) does not exist in the array."); } for(int i = rightindex; i>prevrightindex; i--){ if(x == arr[i]){ System.out.println("The element(x) is found in the index "+i+"."); break; } } } }

3rd Oct 2019, 3:58 PM
stephen haokip
stephen haokip - avatar
1 Answer
+ 1
Can you please write your code in Sololearn playground so we can check what exception is coming.
3rd Oct 2019, 4:07 PM
A͢J
A͢J - avatar