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

私の精神的なデバッグスキルは、次の行が例外をスローしていることを示しています。

int j = Convert.ToInt32(choice2);

Console.Read()前に述べたように in を入れると、その行はすぐには実行されず、例外のスローが遅れます。

この行に整数ではないものを入力した場合:

string choice2 = Console.ReadLine();

FormatException次の電話でを受け取りConvert.ToInt32ます。

値が渡されたときにaがスローされることを示す場所については、ドキュメントをConvert.ToInt32参照してください。FormatExceptiondoes not consist of an optional sign followed by a sequence of digits (0 through 9).

問題を解決するには、使用しますInt32.TryParse(または、有効な整数を入力してください)。これは、例外をスローするのではなく、解析の成功または失敗を示すブール値を返します。

また、StackOverflow へようこそ! 役に立つと思う回答に賛成票を投じ、質問を最もよく解決する回答を受け入れるようにしてください。

于 2013-10-25T18:21:32.697 に答える
3

なぜそれらの余分なものConsole.Read()がそこにあるのですか?returnユーザーが何度も押すため、プログラムが壊れています

    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 に答える