繁体   English   中英

找不到二维数组中的项目

[英]Can't find items in a 2-D array

我正在尝试制作一个程序,用户在其中输入邮政编码的第一部分,即3个或4个字符(我知道可以是2个字符,但我可以在以后加上),并且该程序将通过一个2D数组并输出与之相关的所有值。 我认为我的逻辑是在二维数组中获取邮政编码的子字符串(该数组是由在前面的代码部分中读取到的CSV文档形成的)。 我在控制台中遇到了一系列错误,我不知道出了什么问题。 只是想在这里发帖,看看是否有人可以帮助我。 以下是负责执行此过程的方法的代码:

public void PostCodeSearch(){
    ReadingFromAFile();
    String StrPstCd = PstCd.getText();
    for (int x = 0; x < twod.length; x++) {
        if (StrPstCd.length() == 3){
            String PstCdSub = twod[x][3].substring(0,2);
            if (StrPstCd.equals(PstCdSub)) {
                text.append("Price = " + twod[x][1] + " " + "Date of Sale: " + twod[x][2] + " " + "Postcode: " + twod[x][3] + "\n");
            }
        }else if(StrPstCd.length() == 4){
            String PstCdSub = twod[x][3].substring(0,3);
            if(StrPstCd.equals(PstCdSub)){
                text.append("Price = " + twod[x][1] + " " + "Date of Sale: " + twod[x][2] + " " + "Postcode: " + twod[x][3] + "\n");
            }// end if
        }

    }// end for
}

最好的猜测,而不用看其余的代码。 假设twod是2d字符串数组,其中d0是销售数组索引,d1是虚数枚举{UNKNOWN,PRICE,DATE,POSTNUMBER}。

public void PostCodeSearch() {
    ReadingFromAFile();
    String StrPstCd = PstCd.getText();

    for (int i = 0; i < twod.length; i++) {
        for (int x = 0; x < twod[i][3].length; x++) {

            if (StrPstCd.length == 3  && twod[i][3].length <= x + 3) {
                String PstCdSub = twod[i][3].substring(x, x + 3);
                if (StrPstCd.equals(PstCdSub)) {
                    text.append("Price = " + twod[i][1] + " " + "Date of Sale: " + twod[i][2] + " " + "Postcode: " + twod[i][3] + "\n");
                }
            } 

            else if(StrPstCd.length == 4 && twod[i][3].length <= x + 4) {
                String PstCdSub = twod[i][3].substring(x, x + 4);
                if (StrPstCd.equals(PstCdSub)) {
                    text.append("Price = " + twod[i][1] + " " + "Date of Sale: " + twod[i][2] + " " + "Postcode: " + twod[i][3] + "\n");
                }
            }

        }
    }
}

您没有检查是否要在试图将StrPstCd与twod [i] [3]范围之外的子字符串进行比较的情况下,只是将字符串索引和doubled单位索引混在一起

实际上应该是这样的

import static java.util.regex.*;

public void PostCodeSearch() {
    ReadingFromAFile();
    String StrPstCd = PstCd.getText();
    Pattern pattern = Pattern.compile("^\\S*" + StrPstCd + "\\S*$");
    for(int i = 0; i<twod.length; ++i) {
        Matcher matcher = pattern.matcher(twod[i][3]);
        if (matcher.matches()) {
            text.append("Price = " + twod[i][1] + " " + "Date of Sale: " + twod[i][2] + " " + "Postcode: " + twod[i][3] + "\n");
            }
        }
    }

暂无
暂无

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

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