In C# Write the program SubscriptExceptionTest in which you use an array of 10 d
ID: 3719687 • Letter: I
Question
In C#
Write the program SubscriptExceptionTest in which you use an array of 10 doubles. Write a try block in which you place a loop that prompts the user for a subscript value and displays the value stored in the corresponding array position or asks the user to quit the program by entering 99. Create a catch block that catches any IndexOutOfRangeException and displays the message: Index was outside the bounds of the array.
This is my code:
But it shows 2/3 correct
using System;
public class SubscriptExceptionTest
{
public static void Main()
{bool isNumValue = false;
int num=0;
do {try
{Console.Write(" Enter a number.");
num = Convert.ToInt32(Console.ReadLine());
numList.DisplayValue(num);
isNumValue=true;}
catch (IndexOutOfRangeException e)
{Console.WriteLine(e.Message + " The value you entered is {0}",num);
Console.WriteLine("Index was outside the bounds of the array");
isNumValue=false;}}
while(isNumValue);}
}
class numList
{
private static double [] value = {20.3, 44.6, 32.5, 46.7, 89.6, 67.5, 12.3, 14.6, 22.1, 13.6};
public static void DisplayValue(int num)
{Console.WriteLine("The value of your entered number is " +
value[num].ToString("C"));}
}
Explanation / Answer
Please find my implementation.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
bool isNumValue = false;
int num=0;
do{
try
{
//Ask the user to enter a number
Console.Write(" Enter a number.");
num = Convert.ToInt32(Console.ReadLine());
numList.DisplayValue(num);
isNumValue=true;
}
catch (IndexOutOfRangeException e)
{
//If the user does not enter a number between 0 and 19, an error message will appear prompting them to try again
Console.WriteLine(e.Message + " The value you entered is {0}",num);
Console.Write("Sorry you must enter a number between 0 and 19");
Console.WriteLine("Please try again and enter another number.");
isNumValue=false;
}
}while(isNumValue);
}
}
class numList
{
private static double [] value = { 20.3, 44.6, 32.5, 46.7, 89.6, 67.5, 12.3, 14.6, 22.1, 13.6 };
public static void DisplayValue(int num)
{
//A number appears when the value is within range.
Console.WriteLine("The value of your entered number is " +
value[num].ToString("C"));
}
}