所以我遇到了我的程序问题。我正在尝试修改BinarySearch,以便我可以得到一对数字。我正在尝试确定排序数组中有多个x的多个实例。我需要只显示屏幕的第一个和最后一个索引。我不断添加一些if语句,但是当我这样做时,我没有得到任何比较。现在,当我尝试返回一对(左,右)时,我得到错误:在该特定代码行上找不到符号。我目前没有任何东西可以检查左或右。我只是想让我的代码编译,但我现在无法让它工作。任何输入都会有所帮助。没有要求你为我做我的工作,只是在正确的方向上稍微推动。
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);
}
}
答案 0 :(得分:3)
这将修复语法错误:
更改
return Pair(left, right);
到
return new Pair(left, right);
^^^
但我没有检查你的代码的逻辑。