从控制台获取用户输入时出现"System.FormatException" - visual c#

hur*_*nhu 2 c# console-application

我正在尝试制作一个命令行程序,它会询问您是否需要快速和长时间发出哔声.我一直System.FormatException在看下面的代码.我马上就遇到了问题Console.WriteLine("how many times should i beep?");.我已经找到了一个修正,console.read();//pause在这一行之后放右.

我的问题是我做错了什么?或者我想在那条线之后暂停?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("how fast would you like the sounds to play?");
        Console.WriteLine("70 = fast and 300 = slow can pick any number inbetween");
        string choice = Console.ReadLine();
        int speed = Convert.ToInt32(choice);
        Console.Write(speed);
        Console.Read();//pause
        Console.WriteLine("how many times should i beep?");
        string choice2 = Console.ReadLine();
        int j = Convert.ToInt32(choice2);
        Console.Write(j);
        Console.Read();//pause
        for (int i = 0 ; i < j; i++)
        {
            Console.Beep(1000, speed);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

tnw*_*tnw 6

我的通灵调试技巧告诉我,这一行是抛出异常:

int j = Convert.ToInt32(choice2);
Run Code Online (Sandbox Code Playgroud)

Console.Read()像你提到,导致该行不会立即执行,并延缓异常抛出之前.

如果您在此行输入的内容不是整数:

string choice2 = Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

您将接到FormatException以下Convert.ToInt32电话.

当您传递的值时,请参阅文档,了解Convert.ToInt32它告诉您的FormatException位置does not consist of an optional sign followed by a sequence of digits (0 through 9).

要解决您的问题,请使用Int32.TryParse(或只是确保输入有效的整数).这将返回一个布尔值,指示解析的成功或失败,而不是抛出异常.

另外,欢迎来到StackOverflow!请务必提供有用的答案,并接受最能解决问题的答案.