簡體   English   中英

程序僅讀取文件的第一行

[英]Program only reads the first line in the file

我正在嘗試讀取一個文件,該文件的第一行包含一個名稱,第二行包含數字。 第三行是名稱,第四行是數字,依此類推。

我在主要方法上進行了測試。 例如,我的文件包含名稱“ Bobby”,並且他的電話號碼是123456,當我運行lookUpEntry(“ Bobby”)時,我應該把他的電話號碼還給我。 如果名稱“ Bobby”是文件上的名字,則此方法有效。 如果不是第一個,則程序似乎無法識別該名稱,並向我返回null。 正在破解它,看不到問題所在。 如果您看到任何請咨詢。 謝謝。

//DirectoryEntry is a class and contains a String name and String telno along with set/ get methods for them. 
private DirectoryEntry[] theDirectory = new DirectoryEntry[100];
private int size = 0;

public void loadData(String sourceName) {
        try {
            Scanner in = new Scanner(new File(sourceName));

            while (in.hasNextLine()){
                String name = in.nextLine();
                String telno = in.nextLine();
                theDirectory[size] = new DirectoryEntry(name, telno);
                size++;
            }
            in.close();
        }catch (FileNotFoundException e){
            System.out.println("File not found.");
        }
    }

public String lookUpEntry(String name) {
        find(name);
        if (find(name) >= 0){
            return theDirectory[find(name)].getNumber();
        }
        else{
            return null;
        }
    }

public int find(String name){
        for (int x=0; x < theDirectory.length; x++){
            if (theDirectory[x].getName().equals(name)){
                return x;
            }
            else{
                return -1;
            }
        }
        return  -1;
    }

以下是文件內容:

艾倫·A

123456

鮑比B

234567

查理C

456789

丹尼爾·D

567891

埃里克·E

787454

在您的find方法中,您遍歷了數組,但是使用了if,else塊。 基本上,如果您要查找的名稱不在索引0處,則代碼將跳轉到else語句並返回-1。

編輯:對不起,無論如何我還是看不到您在主代碼中使用該功能...還是應該解決的問題。

編輯2:這不是您的主要方法...再次刮擦...

固定代碼:

public int find(String name){
    for (int x=0; x < theDirectory.length; x++){
        if (theDirectory[x].getName() != null && theDirectory[x].getName().equals(name)){
            return x;
        }
    }
    return  -1;
}

在查找中找到else語句。 第一次檢查后返回-1。 查找應為:

public int find(String name){
    for (int x=0; x < theDirectory.length; x++){
        if (theDirectory[x].getName() != null && theDirectory[x].getName().equals(name)){
            return x;
        }
    }
    return  -1;
}

如果您要查找的不是第一個元素,則從public int find(String name)方法返回-1

這是它的樣子

public int find(String name) {

    for (int i=0; i<size; i++)
        if (theDirectory[i].getName() != null && theDirectory[i].getName().equals(name))
            return i;
    return -1;
}

暫無
暫無

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

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