簡體   English   中英

知道為什么此掃描儀接下來閱讀不起作用

[英]Any idea why this scanner read next won't work

我正在嘗試制作一個從初始大小開始的數組,可以將條目添加到其中。 (我必須使用一個數組)。 要打印數組,我必須執行以下代碼:

public String printDirectory() {
        int x = 0;
        String print = String.format("%-15s" + "%-15s" + "%4s" + "\n", "Surname" , "Initials" , "Number");
//      Sorts the array into alphabetical order
//      Arrays.sort(Array);
        while ( x < count ){
            Scanner sc = new Scanner(Array[x]).useDelimiter("\\t");
            secondName[x] = sc.next();
            initials[x] = sc.next();
            extension[x] = sc.next();
            x++;
        }

        x = 0;
        while ( x < count){
            print += String.format("%-15s" + "%-15s" + "%4S" + "\n", secondName[x] , initials[x] , extension[x]);
            x++;
        }
        return print + "" + Array.length;


    }

請忽略return語句上多余的Array.length。

無論如何,這都可以正常工作,首先,數組會讀取一個文件,該文件的格式類似於NameInitialsnumber。

所以我嘗試制作一個newEntry方法,當我想打印數組時會導致問題。 當我添加新條目時,如果數組太小,它將使數組變大並添加條目。 我制定了一些方法來確保它能夠正常工作。 此方法的以下代碼是:

public void newEntry(String surname, String in, String ext) {

        if (count == Array.length) {
            String entry = surname + "\t" + in + "\t" + ext;
            int x = Array.length + 1;
            String[] tempArray = new String[x];
            System.arraycopy(Array, 0, tempArray, 0, Array.length);
            Array = tempArray;
            Array[count] = entry;
            Arrays.sort(Array);
        } else {
            String entry = surname + "\t" + in + "\t" + ext;
            Array[count] = entry;
            Arrays.sort(Array);
        }
        count++;
    }

問題是,當我隨后調用printDirectory方法時,sc.next()出現了問題。 錯誤消息如下:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
    at ArrayDirectory.printDirectory(ArrayDirectory.java:106)
    at ArrayDirectory.main(ArrayDirectory.java:165)

我對編碼真的很陌生,不知道出什么問題了。 我知道新條目有問題,但不確定。 非常感謝您的幫助。 謝謝。

看來您的其他數組secondNameinitialsextension不夠大。

您還需要使它們更大。 甚至更好的是,當您對此稍加思考時,您會發現您根本不需要它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM