Code for Binary Search. After added function "takeEle" ... code is not running

import java.util.*;
public class Main {
public static void main(String args[]) {
System.out.println(“takeinput”);
int Array[] = takeInput();
System.out.println(“takeinput”);
int keyy = takeEle();
System.out.println(Binar_search(Array, 0, Array.length-1, 6));
}

public static int Binar_search(int[] arri, int lo, int hi, int ele){
	int mid = (lo+hi)/2;
	if(lo>hi){
		return -1;
	}		
	while(lo<=hi){
		if(ele < arri[mid]){
			hi = mid-1;
		}else if(ele == arri[mid]){

			break;
		}else{
			lo = mid+1;
		}
		mid = (lo+hi)/2;
	}
	return mid;
}

public static int[] takeInput(){
	Scanner scn = new Scanner(System.in);
	int N = scn.nextInt();
	int[] array = new int[N];
	for(int i =0; i<N;i++){
		array[i] = scn.nextInt();
		
	}
	return array;
}

public static int takeEle(){
	Scanner scnn = new Scanner(System.in);
	int n = scnn.nextInt();
	return n;
}

}

used scnn instead of scn

Sorry, I didn’t get you.

Note: Locally same code is running but on coding blocks it is not running

@vashisthdeepak928,

Don’t use statements such as: System.out.println(“takeinput”);
Use only 1 scanner object when submitting code. Make the scanner object global but don’t make multiple objects of the scanner class.

Your code giving wrong answer for the input:
5
1
2
3
4
5
6
Correct answer: -1
Your answer: 4

I have modified your code so please make changes to that only: https://ide.codingblocks.com/s/223969

@vashisthdeepak928,

If the element is not present you have print -1, as mentioned in the question statement.

I complied your code & this is giving default answer 4 only.

@vashisthdeepak928,
For the input:
10
1 2 3 4 5 6 7 8 9 10
9
Its giving the correct answer 8.
What input did you give?

5
1 2 3 4 5
6
Output was 4

@vashisthdeepak928,
Yes you have to return -1 if the element is not found, there was an error in your code.

https://ide.codingblocks.com/s/224078 I have corrected your code and highlighted the line where there was an error. Kindly check. :slight_smile:

Thank you for your time and support.

@vashisthdeepak928,
Please mark the doubt as resolved and please give a rating as well.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.