我是java的新手。我正在尝试使用顺序搜索和二进制搜索。我可以成功加载数组,但我的搜索错误了。我不明白我做错了什么。我的两种方法都有问题吗?
package stu.paston.program6;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InventoryData
{
private int[] invData = new int[200];
private int count = 0;
InventoryData(){}//Constructor
public void loadArray()
{
double partNum;
double price;
try
{
String filename = "inventoryPricing.dat";
Scanner infile = new Scanner (new FileInputStream(filename));
while (infile.hasNextInt())
{
invData[count] = infile.nextInt();
partNum = infile.nextDouble();
price = infile.nextDouble();
++count;
}
infile.close();
}
catch (IOException ex)
{
count = -1;
ex.printStackTrace();
}
}
public int seqSearch(int[] invData, int value)
{
for (int i : invData)
{
if (i==value)
{
return i;
}
}
return -1;
}
public int binSearch(int[] invData, int value, int first, int last)
{
if (first > last)
return -1;
int middle = (first + last) / 2;
if (invData[middle] == value)
return middle;
else if (invData[middle] > value)
return binSearch(invData, value, first, middle-1);
else
return binSearch(invData, value, middle+1, first);
}
public int getCount()
{
return count;
}
public int getOneDataNum(int index)
{
if (index >=0 && index < count)
return invData[index];
else
return -1;
}
}// End InventoryData
package stu.paston.program6;
import java.util.Scanner;
public class MainClass
{
public static void main(String[] args)
{
InventoryData productData = new InventoryData();
Scanner myScanner = new Scanner(System.in);
int index;
productData.loadArray();
System.out.println("What is the part number you are looking for ->");
index= myScanner.nextInt();
if (productData.seqSearch(null, index)>=0)
System.out.printf("Sequential fount part number #d and the price is %d", index, productData.seqSearch(null, index));
else
System.out.printf("Sequential did not find part number %d", index);
if (productData.binSearch(null, index, index, index)<=0)
System.out.printf("\nBinary fount part number #d and the price is %d", index, productData.binSearch(null, index, index, index));
else
System.out.printf("\nBinary did not find part number %d", index);
myScanner.close();
}
}
答案 0 :(得分:1)
您正在将空引用传递给seqSearch
:
productData.seqSearch(null, index)
当然你会得到一个NullPointerException。
更改
public int seqSearch(int[] invData, int value)
到
public int seqSearch(int value)
您的班级已有invData
成员。
同时更改
public int binSearch(int[] invData, int value, int first, int last)
到
public int binSearch(int value, int first, int last)