所以我有此代码,您可以在其中输入“区域代码”,然后输入您希望通话多长时间。基本上,这是一个简单的计算器,它会根据您的区号确定 call 的费用。如果输入无效的区号,我很难弄清楚如何保持循环运行。到目前为止,如果我输入了无效的区号,则整个程序将仅在命令提示符下结束。这是代码:
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
中的条件完成为止。在您的情况下,您需要在do
语句中添加对pohne编号的检查,并且要知道此人是否选择了正确的值,可以执行Array.FindIndex()
:
这将是您的do-while
循环,同时我也更改了x
的index
尝试将名称用于具有某些含义的变量。 (索引还是不完美)
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
的数量是一个好习惯。
关于c# - 有关在C#中执行while循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60356487/