C# toUpper()方法导致输入异常
我希望我的程序的用户能够重复一个操作,直到他们通过输入某个字符串指示程序停止运行。我试图允许用户通过使用以下命令输入单词stop来停止程序:C# toUpper()方法导致输入异常,c#,try-catch,C#,Try Catch,我希望我的程序的用户能够重复一个操作,直到他们通过输入某个字符串指示程序停止运行。我试图允许用户通过使用以下命令输入单词stop来停止程序: If (sequenceSelector.ToUpper().Contains("stop")) { //code to do stuff here } 目前,变量sequenceSelector唯一可以访问的位置是封装在这个try块中 try { int sequenceSelector
If (sequenceSelector.ToUpper().Contains("stop"))
{
//code to do stuff here
}
目前,变量sequenceSelector唯一可以访问的位置是封装在这个try块中
try
{
int sequenceSelector = Convert.ToInt32(Console.ReadLine());
if (sequenceSelector <=0)
{
throw new IndexOutOfRangeException();
}
String outputString = "[" + sequenceSelector.ToString() + "]: ";
for (int i = 0; i < sequenceSelector; i++)
{
outputString = outputString + fibonacciSequence.GetValue(i).ToString() + ", ";
}
Console.WriteLine(outputString);
return sequenceSelector;
}
这会导致一个问题,因为其中一个catch块相关:
catch (FormatException)
{
Console.WriteLine("Invalid input detected! Please enter a number that is not <=0 and not > 20");
return null;
}
这将防止用户输入任何非数字字符,因为sequenceSelector必须是int,程序才能正常运行
我希望能够让用户输入单词stop作为程序的一部分。如何绕过异常处理来执行此操作?您需要首先检查Console返回的字符串中是否包含stop。ReadLine:
sequenceSelector.ToUpper不起作用,因为sequenceSelector是一个int。即使它起作用,结果也不会包含stop,而是stop。将sequenceSelector设置为字符串,并使用以下命令检查它是否可转换为int:
ToUpper使字符串大写。与小写的stop相比,stop不起作用。我的印象是,它将文本转换为大写以使其成为大写insensitive@Harry字符串本身既不区分大小写,也不区分大小写。比较可以是其中之一,但不能是字符串本身。stop.ToUpper返回一个新的字符串stop。啊,谢谢@RenéVogt的建议。这个问题需要一个更好的标题。实际上,问题的标题与实际问题的主体没有任何关系。我只是不知道它应该是什么,我忘了提到这段代码在一个私有的静态int中?CaptureInitialNumber,因此此方法返回时会出现错误。并非所有代码路径都返回值。。如何避免这种情况?
string input = Console.ReadLine();
if (input.ToUpper().Contains("STOP"))
return; // or do something to leave the loop
// now you now it's not "stop" -> parse it
int sequenceSelector = Convert.ToInt32(input);
string sequenceSelector = Console.ReadLine();
int intValue;
if(int.TryParse(sequenceSelector, out intValue))
{
if (intValue <= 0)
{
throw new IndexOutOfRangeException();
}
String outputString = "[" + sequenceSelector + "]: ";
for (int i = 0; i < intValue; i++)
{
outputString = outputString + fibonacciSequence.GetValue(i) + ", "; // you can omit the call to ToString, it´s called implictely by the runtime
}
Console.WriteLine(outputString);
return intValue;
}
else if(sequenceSelector.ToUpper().Contains("STOP")) { ... }