Converting from char to int

tofu

I am trying to apply binary search on a string which contains integers. This is my code

public class abcd {
public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    String num="";
    for(int i=0;i<5;i++){
        num += input.next();
    }
    if(bs(5,num))
        System.out.println("Yep");
    else
        System.out.println("Nope");
}
public static boolean bs(int key,String N){
    int low=0,high=N.length()-1,mid;
    while(high>=low){
        mid = (high+low)/2;
        if(N.charAt(mid) == key)
            return true;
        else if(N.charAt(mid) < key)
            low = mid+1;
        else
            high = low-1;
    }
    return false;
}
}

bs is the binary search method.My input is already sorted. Now I wish to find if 5 was entered but even if 5 is included as input, I always get "Nope" as output which implies that bs always returns false.

I understand that charAt returns a char and so that is where the problem is. But then if I wish to convert that char to an int, what should I do? For example, how do I convert '4' to 4?

Phil

Yes, you are trying to compare chars with ints which wont work. How about only using chars?

public static boolean bs(char key,String N){

and call

bs('5', '25789');

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related