2

我正在尝试制作一个命令行程序,它会询问您是否希望它发出哔哔声。我继续阅读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);
        }
    }
}
4

4 回答 4

6

My psychic debugging skills tell me that it's this line throwing the exception:

int j = Convert.ToInt32(choice2);

Putting the Console.Read() in like you mentioned before that causes that line not to execute immediately and delaying the throwing of the exception.

If you input something that isn't an integer on this line:

string choice2 = Console.ReadLine();

You will get a FormatException on the following Convert.ToInt32 call.

See the documentation for Convert.ToInt32 where it tells you a FormatException is thrown when the value you pass does not consist of an optional sign followed by a sequence of digits (0 through 9).

To solve your issue, use Int32.TryParse (or just make sure you enter a valid integer). That will return a boolean indicating the success or failure of the parsing rather than throwing an exception.

Also, welcome to StackOverflow! Be sure to upvote answers you find helpful and accept the one that best resolves your question.

于 2013-10-25T18:21:32.697 回答
3

why are those extra Console.Read() in there? They are breaking your program, because the user will press return too many times

    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.WriteLine(speed);
    Console.WriteLine("how many times should i beep?");
    string choice2 = Console.ReadLine();
    int j = Convert.ToInt32(choice2);
    Console.Write(j);
    for (int i = 0; i < j; i++)
    {
        Console.Beep(1000, speed);
    }
于 2013-10-25T18:22:14.277 回答
0

实际上,您需要做的就是删除Read()您投入的那些暂停。我可能还会将Write()调用更改为WriteLine()调用。

如果您坚持在那里“暂停”,您也可以将呼叫更改为Read()呼叫。ReadLine()

于 2013-10-25T18:30:41.513 回答
-1

尝试这个:

    Console.Read();
    string choice2 = Console.ReadLine();
于 2013-10-25T18:30:03.247 回答