Question

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;...

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

  • by adding a Try Catch code to three of them.
  • Now when you do the 3 nonsense things, you should catch the errors and use the returned error Message property (from your throw code over in the car class) and use that message property to update your ErrorMessage variable. If you do this correctly, then the DisplayCarState method will not say “all is well” but will instead display this unique error message.
  • When you catch the error

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.

Solutions

Expert Solution

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.


Related Solutions

Given code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public...
Given code: 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;...
Given the partially coded project: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace...
Given the partially coded project: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StaticHW {    class Program { static void Main(string[] args) { // will have 3 Dogs Dog[] allDogs = new Dog[3]; allDogs[0] = new Dog(20f, 10f, "Fido"); allDogs[1] = new Dog(40f, 20f, "Percy"); allDogs[2] = new Dog(70f, 30f, "Snoopy"); // comment out the next 3 lines until you have written the Dog class and the code runs ok // then put these 3 lines...
Patient.cs : //namespace using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //application namespace namespace...
Patient.cs : //namespace using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //application namespace namespace ConsoleApp_Patient { class Patient //C# class { //private fields for patientid, lastname,firstname, age, and email. private int patientid; private string lastname; private string firstname; private int age; private string email; //public data items for each of these private fields with get and //set methods public int PatientID //Public field for patientid { get { return patientid; } set { patientid = value;//set patinetid }...
Patient.cs : //namespace using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //application namespace namespace...
Patient.cs : //namespace using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //application namespace namespace ConsoleApp_Patient { class Patient //C# class { //private fields for patientid, lastname,firstname, age, and email. private int patientid; private string lastname; private string firstname; private int age; private string email; //public data items for each of these private fields with get and //set methods public int PatientID //Public field for patientid { get { return patientid; } set { patientid = value;//set patinetid }...
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Assignment07 { class Dog { public void...
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Assignment07 { class Dog { public void bark(string dogsName) { int barking =5; while(barking < 5)    Console.WriteLine(dogsName + " is barking"); } public void run(string dogsName) { int running = 10; while(running > 10) Console.WriteLine(dogsName + " is running"); } } class Program { static void Main(string[] args) { Dog fido = new Dog(); fido.bark("Fido"); fido.run("Fido"); Console.Write("Hit any key to close"); Console.ReadKey(true); } } } need to create 2 while...
USING ACI 318 Codes Problem #3: Design the RC beam given the information below. Ensure that...
USING ACI 318 Codes Problem #3: Design the RC beam given the information below. Ensure that the reinforcement fits in the section, and that the section is tension controlled (i.e., phi = 0.90). Simply supported 20 ft beam. w = 1 kip/ft (dead, does not include self-weight), 1.5 kip/ft (live); f'c = 5,000 psi; fy = 60 ksi; b = 14"; d = 28"; #3 Transverse Reinforcement. Problem #4: Given the same information above, however Mu = 360 kip-ft; b...
The U.S. Postal Service began using five-digit zip codes in 1963. Every post office was given...
The U.S. Postal Service began using five-digit zip codes in 1963. Every post office was given its own zip code, which ranged from 00601 in Adjuntas, Puerto Rico, to 99950 in Ketchikan, Alaska. a. If the only five-digit zip code that could not be used was 00000, how many zip codes were possible in 1963? b. Some five-digit zip codes are prone to errors because they are still legal five-digit zip codes when read upside down. When this happens, a...
Based on the descriptions given below, write the JavaScript codes to calculate the amount to be...
Based on the descriptions given below, write the JavaScript codes to calculate the amount to be paid for books purchased.  Declare all the variables used in this program.  Ask the user to key-in the book code using a prompt() method. Store the value in a variable named book_code.  Ask the user to key-in the number of books purchased using a prompt() method. Store the value in a variable named book_qty.  Ask the user whether they have...
Write a Java program to encrypt the following message using the RC4 cipher using key CODES:...
Write a Java program to encrypt the following message using the RC4 cipher using key CODES: Cryptography is a method of protecting information and communications through the use of codes so that only those for whom the information is intended can read and process it. Instead of using stream length 256, we will use length 26. When encrypting, let A = 0 to Z = 25 (hence CODES = [2 14 3 4 18]). Ignore spaces and punctuations and put...
Using C#, modify the codes below to do the following: Develop a polymorphic banking application using...
Using C#, modify the codes below to do the following: Develop a polymorphic banking application using the Account hierarchy created in the codes below. Create an array of Account references to SavingsAccount and CheckingAccount objects. For each Account in the array, allow the user to specify an amount of money to withdraw from the Account using method Debit and an amount of money to deposit into the Account using method Credit. As you process each Account, determine its type. If...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT