C# Debugging help // Prevents non-numeric data entry // Then prevents division b
ID: 3816161 • Letter: C
Question
C# Debugging help
// Prevents non-numeric data entry
// Then prevents division by 0
using System;
using static System.Console;
class DebugEleven02
{
static void Main()
{
int num = 0, denom = 0;
double result;
bool dataEntryIsValid;
while(!dataEntryIsValid)
{
try
{
DataEntry(num, denom);
dataEntryIsValid = true;
}
catch(FormatException e)
{
WriteLine("Invalid entry - please enter numbers");
}
}
try
{
result = num * 1.0 / denom;
WriteLine("Division is successful");
}
catch(DivideByZeroException e)
{
WriteLine("Division failed")
result = 0;
}
WriteLine("Result is {0}", result);
}
public static void DataEntry(out int num, out int denom)
{
Write("Enter a number ");
if(!int.TryParse(ReadLine, out num))
Console.WriteLine("Numerator was set to 0");
Write("Enter a number to divide into the first ");
if(int.TryParse(ReadLine(), out denom))
WriteLine("Denominator was set to 0");
}
}
Explanation / Answer
Below are the errors in the program: -
1. semi colon was missed on line 31.
2. At Line 16 DataEntry() function signature must have out variables.
3. dataEntryIsValid needs to be initialized with false.
4. At line no. 39. function TryParse(ReadLine, out num), Readline must be called as a function Readline()
5. At line 42 in if block there not operator is needed , we are checking if the denominator is not given or proper.(not int)
6. Divide by Zero Exception was not thrown automatically . Fixed this.
I am assuming there is no issue in formatting of the output. I have not considered this as a bug here...
here is the corrected code: -
// Prevents non-numeric data entry
// Then prevents division by 0
using System;
using static System.Console;
class DebugEleven02
{
static void Main()
{
int num = 0, denom = 0;
double result;
bool dataEntryIsValid = false;
while(!dataEntryIsValid)
{
try
{
DataEntry(out num, out denom);
dataEntryIsValid = true;
}
catch(FormatException e)
{
WriteLine("Invalid entry - please enter numbers");
}
}
try
{
result = num * 1.0 / denom;
if(denom == 0) {
throw new DivideByZeroException();
}
WriteLine("Division is successful");
}
catch(DivideByZeroException e)
{
WriteLine("Division failed");
result = 0;
}
WriteLine("Result is {0}", result);
}
public static void DataEntry(out int num, out int denom)
{
Write("Enter a number ");
if(!int.TryParse(ReadLine(), out num))
Console.WriteLine("Numerator was set to 0");
Write("Enter a number to divide into the first ");
if(!int.TryParse(ReadLine(), out denom))
WriteLine("Denominator was set to 0");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.