简体   繁体   English

如何使用二进制搜索在jTable中查找价格?

[英]How can I use binary search to find Price in jTable?

I want to do a very basic binary search to search for Price, which is at column 4 in my jTable1. 我想做一个非常基本的二进制搜索来搜索Price,它位于jTable1的第4列。 Here is the code I have tried to use so far to no avail. 到目前为止,这是我尝试使用的代码。 There is also a picture below. 下面也有一张图片。

public class BinSearch {

    public static int binarySearch(ArrayList<String> name, int low, int high, String key) {

        if (low <= high) {
            int mid = (low + high) / 2; //get mid point
            if (name.get(mid).equals(key)) {
                return mid;
            } else if ((key.compareTo(name.get(mid))) < 0) {
                return binarySearch(name, low, mid - 1, key);
            } else {
                return binarySearch(name, mid + 1, high, key);
            }
        } else {
            return -1;
        }
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        //get contents from columns:
        ArrayList<String> st = new ArrayList<String>();
        int rowCount = jTable1.getRowCount();
        String fPrice;
        int rowIndex = 0; //start from row 0
        int colIndex = 4; //Price is at column 4
        boolean emptyFlag = false;
        do {
            fPrice = (String) jTable1.getValueAt(rowIndex, 1);
            if (fPrice != null && fPrice.length() != 0) {
                st.add(fPrice);
                rowIndex++;
            } else {
                emptyFlag = true;
            }
        } while (rowIndex < rowCount && !emptyFlag);
        Collections.sort(st); //sort the list
        String key = jTextField4.getText(); //get the search keyword
        int low = 0;
        int high = st.size() - 1;
        int searchResult = BinSearch.binarySearch(st, low, high, key);
        print searchResult;
    }
}

在此处输入图片说明

The program will run, but entering any values and clicking Search will not do anything. 该程序将运行,但是输入任何值并单击“搜索”不会执行任何操作。 I'm a very basic beginner still learning Java with NetBeans, I don't know if I have even put the code in the right area or if the sorting has worked correctly. 我是一个非常基础的初学者,仍然在学习NetBeans的Java语言,我不知道我是否将代码放在正确的区域内,或者排序是否正确。 Any help to get me unstuck would be appreciated. 任何使我解脱的帮助将不胜感激。 Thank you. 谢谢。

You are defining the colIndex, but you never use it. 您正在定义colIndex,但从未使用过。

Do you maybe want to use it in this line instead of the 1? 您是否想在此行中使用它而不是1?

fPrice = (String)jTable1.getValueAt(rowIndex, 1);

Also you can not expect, that your ArrayList is ordered. 您也不能期望ArrayList是有序的。 I am not sure, if your binary search works, when it is not ordered. 我不确定,如果您的二进制搜索有效,何时不订购它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM