在数组中搜索值

问题描述 投票:0回答:1

我在C#中有一个数组生成长度为5的随机数组。我已经用这种方式声明了

int[] array = new int[5]

我应该搜索一个数组,打开一个输入对话框,然后输入任何值。如果找到了数字,或者显示未找到,则应该给我输出并继续运行直到我输入正确的数字。

我有这样的代码,它给了我一些我不需要的价值。我怎样才能实现满足我的条件?提前致谢。

    private void btnSearch_Click(object sender, EventArgs e)
    {
        //use InputBox dialog to input a value.
        //Search for the value in the array.
        //If found, display "Found!", otherwise
        //display "Not found!" when there is no match.

        for (int i = 0; i < array.Length; i++)
        {
            InputBox inputDlg = new InputBox("Search for array value " + (i + 1));
            if (inputDlg.ShowDialog() == DialogResult.OK)
            {
                if (array[i] == Array.IndexOf(array, 5))
                {
                    array[i] = Convert.ToInt32(inputDlg.Input);
                }
                tbxOutput.AppendText("Value found: " + array[i] + Environment.NewLine);
            }

            else
            {
                tbxOutput.AppendText("Value not found" + Environment.NewLine);
            }
        }
c# arrays for-loop search
1个回答
0
投票

如果我理解正确,你有一个包含5个值的数组,并且你想检查它是否包含给定值。那是对的吗?如果是,你必须循环遍历你的数组,并在你发现它时将一个布尔值标记为true

private void btnSearch_Click(object sender, EventArgs e) {

    // loop until you call break
    while(true) {

        // ask for a value
        InputBox inputDlg = new InputBox("Search for array value " + (i + 1));

        try {
            int value = Convert.ToInt32(inputDlg.Input);

            // Check if value is in the array and display the appropriate message
            if(isInArray(array, value)) {
                tbxOutput.AppendText("Value found: " + value + Environment.NewLine);
                // break to exit from the while loop
                break;
            } else {
                tbxOutput.AppendText("Value not found" + Environment.NewLine);
            } 

        } catch (OverflowException) {
            tbxOutput.AppendText("OverflowException parsing input to int" + Environment.NewLine);
        } catch (FormatException) {
            tbxOutput.AppendText("FormatException parsing input to int" + Environment.NewLine);
        }   

    }
}

isInArray方法:

// this method returns true if the given value is in the array
private static boolean isInArray(int[] array, int valueToFind) {
    boolean found = false;
    int currentValue;
    for (int i = 0; i < array.Length; i++) {
        currentValue = array[i];
        if(currentValue == valueToFind) {
            found = true;
            break;
        }
    }
    return found;
}
© www.soinside.com 2019 - 2024. All rights reserved.