java - 编译器错误? Java二分查找

标签 java binary-search

所以我的程序遇到了问题。我正在尝试修改 BinarySearch 以便获得一对数字。我试图确定排序数组中的何处有数字 x 的多个实例。我需要在屏幕上显示第一个和最后一个索引。我不断添加几个 if 语句,但是当我这样做时,我没有进行任何比较。现在,当我尝试返回 Pair(left, right) 时,我收到错误:在该特定代码行上找不到符号。我目前没有任何东西可以检查左侧或右侧。我只是想让我的代码编译,但现在无法让它工作。任何输入都会有帮助。并不是要求你为我做我的工作,只是在正确的方向上稍微插入一下。

import java.util.*;
import java.io.*;

public class Test_BinarySearchDup{

private static class Pair{
    public int left;
    public int right;

    public Pair(int left, int right){
        this.left = left;
        this.right = right;
    }
}

public static void main(String[] args) throws IOException{
    String file = args[0];
    int x = Integer.parseInt(args[1]);
    Scanner fin = new Scanner(new FileReader(file));
    int count = 0;
    while(fin.hasNext()){
        fin.nextInt();
        count++;
    }
    fin.close();

    int[] array = new int[count];

    fin = new Scanner(new FileReader(file));
    while(fin.hasNext()){
        for(int i = 0; i < array.length; i++){
            array[i] = fin.nextInt();
        }
    }
    fin.close();

    Pair numbers =  BinarySearchDup(array, x, 0, (array.length - 1));
    System.out.println("[" + numbers.left + "," + numbers.right + "]");
}

public static Pair BinarySearchDup(int[] A, int x, int low, int high){
    int mid = (low + high) / 2;
    int left = 0, right = 0;
    while(low <= high){
        mid = (low + high) / 2;
        if(A[mid] == x){ //if A[mid] == x we need to check left and right to make sure that there are no other copies of the number
            //checking to the left
            return BinarySearchDup(A, x, low, mid - 1);
        }
        else if(A[mid] < x)
            return BinarySearchDup(A, x, mid + 1, high);
        else
            return BinarySearchDup(A, x, low, mid - 1);
    }
    return new Pair(left, right);
}
}

最佳答案

这将修复您的语法错误:

改变

return Pair(left, right);

return new Pair(left, right);
       ^^^ 

不过,我还没有检查你的代码的逻辑。

关于java - 编译器错误? Java二分查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15868735/

相关文章:

java - 错误 "org.postgresql.Driver is not a valid javax.sql.DataSource implementation"不会影响任何内容。如何去除它?

java - Spring通过枚举来选择bean配置属性

c++ - 使用迭代器位置的线性和二进制搜索

c - 二分查找修改

python - 获取区域包围的第一个和最后一个值的索引

java - 使用 GUI swing JFrame 作为其父级创建 JDialog?

java - 共享可绘制文件夹中的 gif 文件

java - 如何在 jUnit 中比较 bundle 和 collectionassert?

java - 标记上的语法错误、结构错误 - 二分搜索方法中的错误

Java二进制搜索递归