本文介绍了选项是/否C#控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在通过控制台为Currency Converter创建一个C#程序.最后,我要插入继续?(是/否)".用户必须在这里进行选择.我已经尝试过了,但是没用
I'm creating a C# program for the Currency Converter by console.At the end I would to insert "Continue? (yes/no)". Here the user have to chose. I've tried this but it doesn't work
float Dollaro = 1.32f, Euro;
float Cambio;
string EuroStr;
Console.Write("Euro: ");
EuroStr = Console.ReadLine();
Euro = float.Parse(EuroStr);
Cambio = Dollaro * Euro;
Console.WriteLine("Dollaro: " + Cambio);
Console.WriteLine("Vuoi continuare? (yes/no)");
Console.ReadLine();
string risposta = Console.ReadLine();
do
{
if (risposta.Equals("Y"))
{
Console.WriteLine("Yes");
break;
}
else if (risposta.Equals("N"))
{
Console.WriteLine("No");
break;
}
} while (risposta == "N");
推荐答案
float Dollaro = 1.32f, Euro, Cambio;
string EuroStr;
ConsoleKeyInfo risposta;
do
{
Console.Write ( "Euro: " );
EuroStr = Console.ReadLine ();
bool result = Single.TryParse ( EuroStr, out Euro );
if ( result )
{
Cambio = Dollaro * Euro;
Console.WriteLine ( "Dollaro: " + Cambio );
} else {
Console.WriteLine ( "Please enter a number" );
}
bool check = false;
do {
Console.Write ( "\nVuoi continuare? (yes/no) " );
risposta = Console.ReadKey ( true );
check = !( ( risposta.Key == ConsoleKey.Y ) || ( risposta.Key == ConsoleKey.N ) );
} while ( check );
switch ( risposta.Key )
{
case ConsoleKey.Y: Console.WriteLine ( "Yes" ); break;
case ConsoleKey.N: Console.WriteLine ( "No" ); break;
}
} while ( risposta.Key != ConsoleKey.N );
我更改了一些内容:
- 如果我输入欧元的字符-
FormatException
.所以我添加了TryParse()
; - 我已将响应从
string
更改为ConsoleKeyInfo
-这样可以更轻松地检查"Y"或"N",而且我认为更清晰,并且没有需要使用ToLower()投射用户输入并将其与字符串进行比较; - 还检查用户是否按"Y"或"N",而输入内容不同,则将出现相同的消息-
Console.Write("\ nVuoicontinuare?(yes/no)");
- if I enter a character for the Euro -
FormatException
. So I've added aTryParse()
; - I've changed the response from
string
toConsoleKeyInfo
- this makes the check for "Y" or "N" easier and I think clearer, and there is no need to cast the user input with ToLower() and compare it with a string; - also a check if the user presses "Y" or "N", while the input is different, the same message will appear -
Console.Write ( "\nVuoi continuare? (yes/no) " );
通常,您应该过滤掉所有来自用户的data \ info(无论如何),以避免出现异常.
In general you should filter all data\info ( whatever ) comes from the user, to avoid exception.
这篇关于选项是/否C#控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!