Change the code to c DriverClass.java package pkgenum; class MyException extends
ID: 3856575 • Letter: C
Question
Change the code to cDriverClass.java
package pkgenum; class MyException extends Exception //MyException class { int a; MyException(int extra) { a=extra; } public String toString(){ return ("Asked for "+ a +" extra gallons.. returning " + "$"+ (a*4) ); } } class Car{ int tank=10; float speed; void pumpGas(int fill) throws Exception { if(fill<0) //if filling fuel is negative number try{ throw new Exception("Invalid fuel quantity "); //throws exception } catch(Exception e) //catch the exception { System.out.println(e) ; } else{ int capacity=15; if((tank+fill)>capacity) //if tank filling is greater than tank capactiy exception thrown { int extra=(tank+fill)-capacity; try{ throw new MyException(extra); } catch(MyException e) { System.out.println(e) ; } } else System.out.println("Tank filled ");
} } }
public class DriverClass { public static void main(String[] args) throws Exception { Car car=new Car(); //test cases car.pumpGas(-8); car.pumpGas(8); car.pumpGas(3); } }
output Output-enum (run) I run : java.lang. Exception: Invalid fuel quantity Asked for 3 extra gallons returning $12 Tank filled BUILD SUCCESSFUL (total time: o seconds )
Explanation / Answer
#include<iostream>
#include<exception>
#include<pkgenum>
using namespace std;
class MyException : public Exception //MyException class
{
int a;
MyException(int extra)
{
a=extra;
}
public String toString()
{
return ("Asked for "+ a +" extra gallons.. returning " + "$"+ (a*4) );
}
}
class Car
{
int tank=10;
float speed;
void pumpGas(int fill)
{
if(fill<0) //if filling fuel is negative number
try
{
throw new Exception("Invalid fuel quantity "); //throws exception
}
catch(Exception e) //catch the exception
{
cout<<e<<endl ;
}
else{
int capacity=15;
if((tank+fill)>capacity) //if tank filling is greater than tank capactiy exception thrown
{
int extra=(tank+fill)-capacity;
try{
throw new MyException(extra);
}
catch(MyException e)
{
cout<<e<<endl;
}
}
else
cout<<"Tank filled "<<endl;
}
}
}
public class DriverClass {
int main()
{
Car car;
//test cases
car.pumpGas(-8);
car.pumpGas(8);
car.pumpGas(3);
return 0;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.