c# - 关于在 C# 中执行 while 循环的问题
问题描述
所以我有这个代码,您可以在其中输入“区号”,然后输入您希望通话的时间。这基本上是一个简单的计算器,可以根据您的区号计算通话费用。如果我输入了无效的区号,我很难弄清楚如何保持循环运行。到目前为止,如果我输入了无效的区号,整个程序只会在命令提示符下结束。继承人的代码:
using System;
using static System.Console;
namespace Chapter6._1
{
class Program
{
static void Main()
{
// array info //
int[] phoneAreacode = { 608, 414, 262, 815, 715, 920 };
double[] phoneCost = { .05, .10, .07, .24, .16, .14 };
// declaring variables //
int x;
int areaCode;
double cost = 0;
int callLength;
bool validAreacode = false;
// start of actual code //
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
x = 0;
while (x < phoneAreacode.Length && areaCode != phoneAreacode[x])
++x;
if(x != phoneAreacode.Length)
{
validAreacode = true;
cost = phoneCost[x];
}
if (validAreacode)
{
Write("Enter in the length of your call: ");
callLength = Convert.ToInt32(ReadLine());
double finalCost = callLength * cost;
WriteLine("Your call to area code " + areaCode + " for " + callLength + " minutes will cost " + finalCost.ToString("C"));
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
}
}
}
解决方案
你可以在do-While
这里做一个:
基本上,当您这样做时,您会do-while
强制执行代码,do
直到完成条件while
。在您的情况下,您需要在语句中添加对 pohne 编号的检查do
,并且要知道该人是否选择了正确的值,您可以这样做Array.FindIndex()
:这将是您的do-while
循环,我也更改了您的x
forindex
尝试使用名称有一定意义的变量。(无论如何索引并不完美)
do
{
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
index = Array.FindIndex(phoneAreacode, w => w == areaCode);
if (index >= 0)
{
validAreacode = true;
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
} while (!validAreacode);
这将是您的整个主要方法:
int[] phoneAreacode = { 608, 414, 262, 815, 715, 920 };
double[] phoneCost = { .05, .10, .07, .24, .16, .14 };
// declaring variables //
int index;
int areaCode;
int callLength;
bool validAreacode = false;
// start of actual code //
do
{
Write("Enter in the area code you want to call: ");
areaCode = Convert.ToInt32(ReadLine());
index = Array.FindIndex(phoneAreacode, w => w == areaCode);
if (index >= 0)
{
validAreacode = true;
}
else
{
WriteLine("YOU MUST ENTER A VALID AREA CODE!");
}
} while (!validAreacode);
Write("Enter in the length of your call: ");
callLength = Convert.ToInt32(ReadLine());
double finalCost = callLength * phoneCost[index];
WriteLine("Your call to area code " + areaCode + " for " + callLength + " minutes will cost " + finalCost.ToString("C"));
如您所见,您还可以删除while
必须循环数组和if-else
有效代码的 。假设当代码到达该点时,该区域是正确的。
尝试删除if-else
.
推荐阅读
- typescript - 如何遍历已定义键的对象并使用键来索引相同类型的对象?
- instagram - 获取 Instagram 直播 RTMP URL 和 Key
- python - 迁移时在 django 中出错
- html - 如何使用 jquery 在导航栏下划线
- nginx - NGINX 配置通过 HTTPS 将流量发送到服务器,NGINX 是客户端
- pandas - Pandas 连接两个数据帧
- installation - Anaconda 安装卡在 Win x86 64 位机器上
- c++ - 冒泡排序函数在 C++ 中不起作用(获取数组的一个索引的垃圾值)
- c++ - 查找最低共同祖先的代码不适用于某些测试用例
- flutter - 无法在颤振中创建广播流