java - 从 char 转换为 int

标签 java char int

我正在尝试对包含整数的字符串应用二分搜索。这是我的代码

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 是二分查找法。我的输入已经排序了。现在我希望查找是否输入了 5,但即使包含 5 作为输入,我总是得到“Nope”作为输出,这意味着 bs 始终返回 false。

我知道 charAt 返回一个 char,这就是问题所在。但是如果我想将该 char 转换为 int,我该怎么办? 例如,如何将“4”转换为 4?

最佳答案

首先使用 Character.forDigit() 将您的 key 转换为字符

public static boolean bs(int intkey,String N){
    char key = Character.forDigit(intkey,10);

    int low=0,high=N.length()-1,mid;
    //...
    //the rest of your function should stay the same
    //...
}

关于java - 从 char 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27160856/

相关文章:

c - 处理包含空格的字符数组

将字符串转换为带有负数的 int

c++ - 为什么整数类型 int64_t 不能持有这个合法值?

python - 值错误 : invalid literal for int() with base 10: 'stop'

从 char 数组构造一个唯一字符数组

Java EE Servlet 重写 servlet 路径

Java的Swing似乎正在改变Card Layout的布局

java - 如何使用 JSP 和 JAVA 读取 URL

java - 在决定使用 volatile 时,实际的锁是否重要?

c - 在 C 中用更多字符扩展字符(不允许覆盖)