In: Computer Science
Given Codes: Program.cs & Car.cs
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary1;
namespace ConsoleCarsExcpeptions
{
class Program
{
static void Main(string[] args)
{
Car myCar = new Car(35); // call constructor and set speed max to
35 (tiny engine!!)
string ErrorMessage = "All is well";
bool done = false; // loop control variable
while (!done)
{
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("start = start engine, stop = stop
engine");
Console.Write("accel = accelerate, brake = brake, q = quit.
Command? :");
Console.ResetColor();
string userInput = Console.ReadLine();
userInput = userInput.ToLower(); // in case user happened to enter
capital letters
Console.Clear(); // each time we get a new command, clear the prior
history from the console
switch (userInput)
{
case "start":
myCar.StartEngine();
break;
case "stop":
myCar.StopEngine();
break;
case "accel":
myCar.Accelerate();
break;
case "brake":
myCar.Decelerate();
break;
case "q":
case "e":
Console.WriteLine("Goodbye");
done = true;
break;
default:
Console.WriteLine("Not a valid input.");
break;
}
// at the end of each command, call this method to show
status
DisplayCarState(ErrorMessage, myCar);
}
Console.ReadLine();
}
private static void DisplayCarState(string msg, Car myCar)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine(msg);
Console.WriteLine("Engine is running: " +
myCar.EngineRunning);
Console.WriteLine("Current speed is: " +
myCar.CurrentSpeedMPH);
Console.ResetColor();
}
}
}
Car.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class Car
{
// fields
private decimal _CurrentSpeedMPH; // the cars current speed
private decimal _MaxSpeedMPH; // the upper limit, the car cannot
exceed this value
private bool _EngineRunning; // true means the engine has been
started and is running, false says engine is off
public Car(decimal maxSpeed) // constuctor, user chooses to set
maxSpeed as they create the object
{
_MaxSpeedMPH = maxSpeed;
_CurrentSpeedMPH = 0;
_EngineRunning = false;
}
public bool EngineRunning // Property to allow reading the current
value
{ get { return _EngineRunning; } }
public decimal CurrentSpeedMPH // Property to allow reading the
current value
{ get { return _CurrentSpeedMPH; } }
public void StartEngine() // method used to start car's
engine
{
_EngineRunning = true;
}
public void StopEngine() // method used to stop car's
engine
{
_EngineRunning = false;
}
public void Accelerate() // method used to increase the cars
speed
{
_CurrentSpeedMPH = _CurrentSpeedMPH + 10; // this method always
tries to increase by 10 mph
if (_CurrentSpeedMPH > _MaxSpeedMPH) // but it can never exceed
the max speed as set in the constructor
{
_CurrentSpeedMPH = _MaxSpeedMPH; // if speed is higher than max,
slow it to max
}
}
public void Decelerate() // this method always tries to decrease
the speed by 5 mph
{
_CurrentSpeedMPH = _CurrentSpeedMPH - 5; // but never lets it go
below 0 and become negative.
if (_CurrentSpeedMPH < 0)
{
_CurrentSpeedMPH = 0;
}
}
}
}
First, modify the car class to throw 3 new exceptions
[1] In the Modify the StartEngine method:
Change the logic such that if the user code calls the StartEngine method when the engine is already started, the StartEngine method will throw a new ApplicationException and that exception should have a Message property set to “Engine is already started.”.
[2] Modify the StopEngine method:
Change the logic such that if the user code calls the StopEngine engine when the engine is already stopped, the StopEngine method will throw a new ApplicationException and that exception should have a Message property set to “Engine is not running.”.
[3] Modify the Accelerate method:
Change the logic such that if the user code gives calls the Accelerate method when the engine is not running, the Accelerate method will throw new ApplicationException and that exception should have a Message property set to “Please start engine.”. (Note that braking should work even if the engine is on or off, so no change is needed for that code.)
[4] Run your program now, and try these 3 nonsensical things (trying to accelerate when the engine is not running, trying to start the engine when it is already started, and trying to stop the engine when it is already stopped) and verify the system pops up “uncaught exception” boxes showing each of your 3 unique error messages. Only when you have all 3 “throws” working, then move on to modify the console program.cs:
So now modify the 3 appropriate cases in your switch statements
catch (ApplicationException e) make sure to declare the name of your new exception object, which is traditionally called e. When you do that, you can get the error message you created in the throw by using e.Message
[5] But once you modify your ErrorMessage to display the new error, that error message will be stuck no matter what good things the user does. To fix this, modify all paths such that when no problem is encountered to overwrite any previous value in the ErrorMessage variable with the standard message "All is well" such that the errors go away after the user moves on and does something that is not an error. In other words, the status message should always be showing current correct status.
Answering only the 1st four sub questions, as per the guidelines.
The modified code for the 1st 3 sub questions are given below. The comments are provided for the better understanding of the logic.
// method used to start car's engine
public void StartEngine()
{
//Check if the engine is already running
if (_EngineRunning)
//If the engine is already running, throw an ApplicationException.
throw new ApplicationException("Engine is already started.");
else
//If the engine is not running, run the engine.
_EngineRunning = true;
}
// method used to stop car's engine
public void StopEngine()
{
//Check if the engine is already running
if (_EngineRunning)
//If the engine is running, stop the engine.
_EngineRunning = false;
else
//If the engine is not running, throw an ApplicationException
throw new ApplicationException("Engine is not running.");
}
// method used to increase the cars speed
public void Accelerate()
{
//Check if the engine is already running
if (_EngineRunning)
{
//If the engine is running, proceed with the logic in accelerating.
// this method always tries to increase by 10 mph
_CurrentSpeedMPH = _CurrentSpeedMPH + 10;
// but it can never exceed the max speed as set in the constructor
if (_CurrentSpeedMPH > _MaxSpeedMPH)
{
// if speed is higher than max, slow it to max
_CurrentSpeedMPH = _MaxSpeedMPH;
}
}
else
//If the engine is not running, throw an ApplicationException
throw new ApplicationException("Please start engine.");
}
The screenshots of the code are given below.
When the program is executed, the exceptions are thrown as shown below.
1. Run the program. Provide start as the input. The program will display the status message. Provide start as the input again. The uncaught ApplicationException will be thrown as below.
2. Run the program. Provide stop as the input. The uncaught ApplicationException will be thrown as below.
3. Run the program. Provide accel as the input. The uncaught ApplicationException will be thrown as below.
For the 4th sub question, the modified code in the switch statement is provided below. This is in the Main method. The comments are provided for better understanding.
switch (userInput)
{
case "start":
//Use the try catch block to catch the Exception.
try
{
myCar.StartEngine();
}
catch(ApplicationException e)
{
//Assign the error message to the variable ErrorMessage
ErrorMessage = e.Message;
}
break;
case "stop":
//Use the try catch block to catch the Exception.
try
{
myCar.StopEngine();
}
catch (ApplicationException e)
{
//Assign the error message to the variable ErrorMessage
ErrorMessage = e.Message;
}
break;
case "accel":
//Use the try catch block to catch the Exception.
try
{
myCar.Accelerate();
}
catch (ApplicationException e)
{
//Assign the error message to the variable ErrorMessage
ErrorMessage = e.Message;
}
break;
case "brake":
myCar.Decelerate();
break;
case "q":
case "e":
Console.WriteLine("Goodbye");
done = true;
break;
default:
Console.WriteLine("Not a valid input.");
break;
}
Once the above changes are made to the program, execute the program in the same way as previously executed. The error messages will be displayed as shown below in the program itself.