これは宿題なので、いくつかのガイダンスを探しています。ユーザーが指定したインデックス値に基づいて配列内の値を返す作業をしています。無効な値の特定の条件と例外処理でループを終了する方法
「99」が入力されたときにプログラムを停止する必要があるのは、try-catch IndexOutOfRangeExceptionをトリガーする値です。 "99"と他の範囲外の値との差異をプログラムが認識することはできません。私はif-elseで試してみましたが、 "99"はまだIndexOutOfRangeExceptionをスローしてループしませんでした。 do-whileの試みもうまくいかなかった。
コードは以下のとおりです。前もって感謝します。
using System;
using static System.Console;
class SubscriptExceptionTest
{
static void Main()
{
double[] array = {20.3, 44.6, 32.5, 46.7, 89.6, 67.5, 12.3, 14.6, 22.1, 13.6};
int i = 0;
while (i != 99)
try
{
Write("Enter a number to see the value in that position. Type 99 to stop: ");
i = Convert.ToInt32(ReadLine());
double arrayVal = array[i];
WriteLine("The value at index {0} is {1}", i, arrayVal);
ReadLine();
}
catch (FormatException fe)
{
throw new FormatException("You did not enter an integer.");
}
catch (IndexOutOfRangeException ie)
{
throw new IndexOutOfRangeException("Index was outside the bounds of the array.");
}
catch (Exception ex)
{
throw new Exception("Error: " + ex.Message);
}
}
}
評価のソフトウェアはまだif文に載っていますが、Visual Studioでは動作しますが、それで十分です。ありがとうございました! ifステートメントの配置が問題でした。時には、この人間がコンピュータのように考えるのは本当に難しいです。 –