按客户端ID搜索无效

时间:2014-11-26 22:06:27

标签: java

当我运行此程序并输入客户端信息时,则决定通过clientID进行搜索,它将始终返回未找到的客户端。

这是选择搜索选项的情况:

case 2: 
    input = JOptionPane.showInputDialog("Enter the client ID to search for: ");
    while(checkSearchClientID(input) == false)
    {   
        input = JOptionPane.showInputDialog("Invalid! Only 9 digits allowed. Re-enter search ID: ");
    }
    searchClient = input;
    searchClient();
    if(foundAt < 0)
    {
        JOptionPane.showMessageDialog(null, "Client not found!");
    }
    else
    {
        OptionPane.showMessageDialog(null, "Found at: " + foundAt);
        client[foundAt].dispClient();
    }
    break;

这是搜索方法

public static void searchClient()
{
    int i = 0;
    while (i < ccount)
    {
        if(searchClient.equals(client[i].clientID))
        {
            foundAt = i;
        }//end if
        i++;        
    }//end while
    foundAt = -1;
}//end searchClient

这是输入客户ID的地方

void getClient()
{
    String input = new String (" ");
    input = JOptionPane.showInputDialog("Enter client ID: ");
        while(checkClientID(input) == false)
        {   
            input = JOptionPane.showInputDialog("Invalid! Only 9 digits allowed. Re-enter client ID: ");
        }//end while
    clientID = Integer.parseInt(input);

1 个答案:

答案 0 :(得分:1)

无论结果如何,public static void searchClient()方法始终将foundAt设置为-1。

public static void searchClient() {
    int i = 0;
    while (i < ccount)
    {
        if(searchClient.equals(client[i].clientID))
        {
            foundAt = i;
        }//end if
        i++;        
    }//end while
    foundAt = -1;  // this always occurs, no matter the result from the while block
}

一种解决方案:在方法的开始处将foundAt设置为-1,而不是结束。

public static void searchClient() {
    foundAt = -1; // ***** here
    int i = 0;
    while (i < ccount)
    {
        if(searchClient.equals(client[i].clientID))
        {
            foundAt = i;
        }//end if
        i++;        
    }//end while
    // foundAt = -1;  // **** not here
}

另外,考虑使用此方法返回 foundAt int,以便它返回结果而不是通过副作用进行更新。