我在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);
}
}
答案 0 :(得分:0)
如果我理解正确,那么您就有1个数组,其中包含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;
}