1)尝试并捕获后我想再次循环它以给出新的数字(“Console.ReadLine(”给出正确的数字“))因为用户没有输入字符串convertable到double 2第二个问题是,当用户提供错误号码时,我想再次循环输入新号码。此版本的程序会向小号或大号号码发送消息并退出
校正
double number=10,11;
Console.WriteLine("Give a number");
string w=Console.ReadLine();
try
{
double d = Convert.ToDouble(w);
}
catch(FormatException)
{
Console.WriteLine("it is not a number");
}
double dd=Convert.ToDouble(w);
if (dd == number)
{
Console.WriteLine("Yes, it is!");
}
else if (number<dd)
{
Console.WriteLine("to big number");
}
else if(number>dd)
{
Console.WriteLine("to small number");
}
Console.ReadLine();
答案 0 :(得分:2)
首先,使用SELECT DeptID, EmpName, Salary
FROM EmpDetails a
WHERE Salary = (SELECT MAX(Salary)
FROM EmpDetails b
WHERE a.DeptID = b.DeptID)
继续询问,直到用户输入有效数字。其次,使用do..while(condition)
检查值是否有效。这比异常处理和转换两次要好。不确定您使用TryParse
的原因,但double
可能更合适。
int
请注意bool valid = false;
do
{
bool newValidState;
Console.WriteLine("Give a number");
string w = Console.ReadLine();
double d;
if (!double.TryParse(w, out d))
{
Console.WriteLine("it is not a number");
newValidState = false;
}
else if (d == number)
{
Console.WriteLine("Yes, it is!");
newValidState = true;
}
else if (wyliczona < wybor) // these conditions seem unrelated to `d`
// are they okay?
{
Console.WriteLine("to big number");
newValidState = false;
}
else if(wyliczona > wybor)
{
Console.WriteLine("to small number");
newValidState = false;
}
else
{
Console.WriteLine("unknown condition. needs work.");
newValidState = false;
}
valid = newValidState;
}
while (!valid);
的使用,这将确保您始终为newValidState
分配新值。这有助于防止由于从未设置值而导致的无限循环。除非每个分支都将valid
设置为值,否则代码将无法编译。
答案 1 :(得分:-1)
试试这个:
var number =3;
do{
Console.WriteLine("Give a number");
string w=Console.ReadLine();
try
{
double d = Convert.ToDouble(w);
}
catch(FormatException)
{
Console.WriteLine("it is not a number");
continue; // not a number starting new iteration of the loop
}
double dd=Convert.ToDouble(w);
if (dd == number)
{
Console.WriteLine("Yes, it is!");
break; // The number guessed exiting loop
}
else if (dd>number)
{
Console.WriteLine("to big number");
}
else if(dd<number)
{
Console.WriteLine("to small number");
}
}
while (true);
Console.ReadLine();