Question

In: Computer Science

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

Solutions

Expert Solution

Working code implemented in C# and appropriate comments provided for better understanding.

Here I am attaching code for all files:

  • Cars.cs
  • Program.cs

Cars.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
{
//Throw application exception when engine is already running
if (_EngineRunning)
{
throw new ApplicationException("Engine is already started.");
}
else
{
_EngineRunning = true;
}
}

public void StopEngine() // method used to stop car's engine
{
//Throw application exception when current speed in miles per hour is not zero
if (_CurrentSpeedMPH != 0)
{
throw new ApplicationException("Please stop car first.");
}
else
{
_EngineRunning = false;
}
  
}


public void Accelerate() // method used to increase the cars speed
{
//Throw application exception when the engine is not running
if (!_EngineRunning)
{
throw new ApplicationException("Please start engine.");
}
else
{
_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;
}
}


}
}

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


// Put try / catch over switch in while loop to catch throws from car class and to set ErrorMessage
bool bHadError = false; // to check if we had an error this loop
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

try
{

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;
} // end switch

}// end try
catch (ApplicationException ex)
{
// Set the ErrorMessage to exceptions message,
// and set error flag to true so we can reset after we display error.
ErrorMessage = ex.Message;
bHadError = true;

} // end catch

// at the end of each command, call this method to show status
DisplayCarState(ErrorMessage, myCar);

if (bHadError) // reset error message now
{
// Reset ErrorMessage to "All is well" and reset error flag
ErrorMessage = "All is well";
bHadError = false;
}
}// end while
Console.ReadLine();

}// end main

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();
}
}
}

Sample Output Screenshots:


Related Solutions

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 }...
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...
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,...
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...
Previous Lab Code files: PersonType.h: #include <string> using namespace std; class personType { public: void print()...
Previous Lab Code files: PersonType.h: #include <string> using namespace std; class personType { public: void print() const; void setName(string first, string middle, string last);    void setLastName(string last);    void setFirstName(string first);    void setMiddleName(string middle);    bool isLastName(string last) const;    bool isFirstName(string first) const; string getFirstName() const;    string getMiddleName() const;    string getLastName() const; personType(string first = "", string middle = "", string last = ""); private: string firstName; string middleName; string lastName; }; PersonTypeImp: #include <iostream>...
CODE: C# using System; public static class Lab6 { public static void Main() { // declare...
CODE: C# using System; public static class Lab6 { public static void Main() { // declare variables int hrsWrked; double ratePay, taxRate, grossPay, netPay=0; string lastName; // enter the employee's last name Console.Write("Enter the last name of the employee => "); lastName = Console.ReadLine(); // enter (and validate) the number of hours worked (positive number) do { Console.Write("Enter the number of hours worked (> 0) => "); hrsWrked = Convert.ToInt32(Console.ReadLine()); } while (hrsWrked < 0); // enter (and validate) the...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating the average sightings from the Total Sightings array float calcAverage(float totalSightings[],int n) {    int i;    float sum=0.0;    for(i=0;i<n;i++)    sum=sum+totalSightings[i];    return sum/n; } int main() {    // n is no. of bird watchers    //flag , flag2 and flag3 are for validating using while loops    int n,i,flag,flag2,flag3;       //ch also helps in validating    char ch;   ...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; //...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; // constants const int FINAL_POSITION = 43; const int INITIAL_POSITION = -1; const int NUM_PLAYERS = 2; const string BLUE = "BLUE"; const string GREEN = "GREEN"; const string ORANGE = "ORANGE"; const string PURPLE = "PURPLE"; const string RED = "RED"; const string YELLOW = "YELLOW"; const string COLORS [] = {BLUE, GREEN, ORANGE, PURPLE, RED, YELLOW}; const int NUM_COLORS = 6; // names...
Complete the code provided to add the appropriate amount to totalDeposit. #include <iostream> using namespace std;...
Complete the code provided to add the appropriate amount to totalDeposit. #include <iostream> using namespace std; int main() { enum AcceptedCoins {ADD_QUARTER, ADD_DIME, ADD_NICKEL, ADD_UNKNOWN}; AcceptedCoins amountDeposited = ADD_UNKNOWN; int totalDeposit = 0; int usrInput = 0; cout << "Add coin: 0 (add 25), 1 (add 10), 2 (add 5). "; cin >> usrInput; if (usrInput == ADD_QUARTER) { totalDeposit = totalDeposit + 25; } /* Your solution goes here */ else { cout << "Invalid coin selection." << endl;...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT