c# - 有没有办法通过让用户选择输入数字退出来退出这个 do while 循环?
问题描述
我创建了一个数组,允许企业输入他们服务的邮政编码,并赋予他们搜索的能力。我想让用户能够输入 0 以退出程序。如何在 do while 循环的“while”部分执行此操作?(我知道以字符串形式输入邮政编码更好)。
我试过把while(lookup != 0)
,我得到一个错误,告诉我名称查找不存在。
int[] zipCodes = new int[5];
for (int i = 0; i < zipCodes.Length; i = i + 1)
{
Console.WriteLine("Enter a 5 digit zip code that is supported in your area");
zipCodes[i] = Convert.ToInt32(Console.ReadLine());
}
Array.Sort(zipCodes);
for (int i = 0; i < zipCodes.Length; i = i + 1)
{
Console.WriteLine("zip codes {0}: {1}", i, zipCodes[i]);
}
do
{
Console.Write("Enter a zip code to look for: ");
Console.WriteLine();
Console.WriteLine("You may also enter 0 at any time to exit the program ");
Int64 lookup = Convert.ToInt64(Console.ReadLine());
int success = -1;
for (int j = 0; j < zipCodes.Length; j++)
{
if (lookup == zipCodes[j])
{
success = j;
}
}
if (success == -1) // our loop changes the -1 if found in the directory
{
Console.WriteLine("No, that number is not in the directory.");
}
else
{
Console.WriteLine("Yes, that number is at location {0}.", success);
}
} while (lookup != 0);
Console.ReadLine();
输入他们提供的邮政编码,并赋予他们搜索的能力。显示输入到数组中的邮政编码,然后选择搜索或退出程序。
解决方案
就像我在上面的评论中所说:您需要在 do while 循环之外定义查找变量,它当前仅存在于其中,因此当条件运行时会导致错误:)
Int64 lookup = 1; //or something other than 0
do
{
...
your code
...
} while (lookup != 0);
推荐阅读
- mysql - LINQ 查询语法操作数应包含 1 列
- javascript - 在 vue.js 中执行 axios.get 时捕获特定元素
- c++ - 将 QTreeView 填充为数据库中的父节点和子节点
- mysql - Wordpress 容器拒绝与 mysql 连接
- r - R:根据不同的值生成表
- c# - 在位图 500x500 上按角度绘制线条
- flutter - -bash:颤振:找不到命令
- xamarin.forms - 可绑定的 ObservableCollection 不更新日历 UI
- python - 打印在文本文档中搜索字符串的结果。PYTHON
- swift - UILabel textColor 属性标记为非空,但默认注释为 nil