Question

In: Computer Science

Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java...

Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java

* description of class Driver here.
*these is the main class where it acts like parent class.

Compiler will execute firstly static method.

import java.util.Scanner;
public class Driver
{
    public static void main (String[] args){
        Scanner stdIn = new Scanner(System.in);
        String user;
        String computer;
        char a = 'y';
        do {
            System.out.println("What kind of Computer would you like?");
            System.out.println("a) Desktop");
            System.out.println("b) Laptop");
            computer = stdIn.next();
            Desktop desktoppp = new Desktop();
            Laptop laptoppp = new Laptop();
            if (computer.equalsIgnoreCase("desktop") || computer.equalsIgnoreCase("a")){
                desktoppp.Desktop();
            }
            else if (computer.equalsIgnoreCase("laptop") || computer.equalsIgnoreCase("b")){
                laptoppp.Laptop();       
            }
            else {
                System.out.println("Follow the instructions!!!");
            }
            System.out.println("Do you want to continue? (Y/N)");
            a = stdIn.next().charAt(0);
     
        } while (a == 'Y' || a == 'y');
        System.out.println("Have a nice day!!!");

    }
}

**
* description of class Laptop here.
*These class will wxtended from main method

it will inherit the properties of Driver

it is Laptop class


import java.util.Scanner;

public class Laptop extends Driver
{
    Scanner stdIn = new Scanner(System.in);
    public void Laptop(){
        String laptbrand;
        String lapttype;
        String laptcpubrand;
        double laptcpuspeed;
        double lapthddcap;
        double laptramcap;
        double laptdispsize;
        double TotalPrice=0;
        double price1, price2, price3, price4, price5, price6, price7;
        //************************************************
        System.out.print("What brand would you like? ");
        laptbrand = stdIn.next();
        System.out.print("Enter a price: ");
        price1 = stdIn.nextDouble();
        System.out.print("What CPU brand would you like? ");
        laptcpubrand = stdIn.next();
        System.out.print("Enter a price: ");
        price3 = stdIn.nextDouble();
        System.out.print("What is your prefered CPU speed would you like? ");
        laptcpuspeed = stdIn.nextDouble();
        System.out.print("Enter a price: ");
        price4 = stdIn.nextDouble();
        System.out.print("How many GB of HDD would you like? ");
        lapthddcap = stdIn.nextDouble();
        System.out.print("Enter a price: ");
        price5 = stdIn.nextDouble();
        System.out.print("How many GB of RAM would you like? ");
        laptramcap = stdIn.nextDouble();
        System.out.print("Enter a price: ");
        price6 = stdIn.nextDouble();
        System.out.print("How many inch display size would you like? ");
        laptdispsize = stdIn.nextDouble();
        System.out.print("Enter a price: ");
        price7 = stdIn.nextDouble();
        //*************************************************
        TotalPrice = price1 + price3 + price4 + price5 + price6 + price7;
        //*************************************************
        System.out.println("Laptop brand: " + laptbrand);
        System.out.println("CPU brand: " + laptcpubrand);
        System.out.println("CPU speed: " + laptcpuspeed + "GHz");
        System.out.println("HDD capacity: " + lapthddcap + "GB");
        System.out.println("RAM capacity " + laptramcap + "GB");
        System.out.println("Display size: "+ laptdispsize + "inches");
        System.out.println("Total Price: " + TotalPrice + "$");
     
    }
}

/**
* description of class desktop here.
*it i will extend the properties of Driver
it is Desktop class which will inherit the properties of Driver
import java.util.Scanner;

public class Desktop extends Driver
{
    Scanner stdIn = new Scanner(System.in);

    public void Desktop(){
        String deskbrand;
        String casetype;
        String deskcpubrand;
        double deskcpuspeed;
        double deskhddcap;
        double deskramcap;
        double deskdispsize;
        double TotalPrice=0;
        double price1, price2, price3, price4, price5, price6, price7;
        //************************************************
        System.out.println("What brand would you like? ");
        deskbrand = stdIn.next();
        System.out.println("Enter a price: ");
        price1 = stdIn.nextDouble();
        //************************************************
        System.out.println("What type of case would you like? Mini, Mid or Full Tower ");
        casetype = stdIn.next();
        System.out.println("Enter a price: ");
        price2 = stdIn.nextDouble();
        //************************************************
        System.out.println("What CPU brand would you like? ");
        deskcpubrand = stdIn.next();
        System.out.println("Enter a price: ");
        price3 = stdIn.nextDouble();
        //************************************************
        System.out.println("What is your prefered CPU speed would you like? ");
        deskcpuspeed = stdIn.nextDouble();
        System.out.println("Enter a price: ");
        price4 = stdIn.nextDouble();
        //************************************************
        System.out.println("How many GB of HDD would you like? ");
        deskhddcap = stdIn.nextDouble();
        System.out.println("Enter a price: ");
        price5 = stdIn.nextDouble();
        //************************************************
        System.out.println("How many GB of RAM would you like? ");
        deskramcap = stdIn.nextDouble();
        System.out.println("Enter a price: ");
        price6 = stdIn.nextDouble();
        //************************************************
        System.out.println("How many inch display size would you like? ");
        deskdispsize = stdIn.nextDouble();
        System.out.println("Enter a price: ");
        price7 = stdIn.nextDouble();
        //*************************************************
        TotalPrice = price1 + price2 + price3 + price4 + price5 + price6 + price7;
        //*************************************************
        System.out.println("Desktop brand: " + deskbrand);
        System.out.println("Case type: " + casetype);
        System.out.println("CPU brand: " + deskcpubrand);
        System.out.println("CPU speed: " + deskcpuspeed);
        System.out.println("HDD capacity: " + deskhddcap);
        System.out.println("RAM capacity " + deskramcap);
        System.out.println("Display size: "+ deskdispsize);
        System.out.println("Total Price: " + TotalPrice + "$");
     
    }
}

Solutions

Expert Solution

Hi

I haven't changed much of your code. I just added a switch case in the main method and throws exception statement which will throw a exception case.

In Laptop and desktop classes i added try and catch block which will find any error in the try block and if an error is found an exception is returned by the catch block.

In this code there is one exception found ie., for double values that is like ram, cpu speed and price, the user might unexpectedly enter a char or string value. Due to that error, the program might terminate. To overcome the sudden termination of program, we use exception handling.

I used try and catch block with Exception class, which will return the exception without terminating the program.

Actually i wanted to add a display function in main method and call it using laptop and desktop classes object but that is not possible because the number of variables of prices differ i.e., price 1 to 6 in laptop and price 1 to 7 in desktop, so i couldn't add that function.

However i have added comments to all the lines.

//import the necessary packages
//utils package is used for input and output
import java.util.Scanner;
import java.io.*;
//Driver class has default access modifier i.e., this class can be accessed by the class
and sub-classes of the same package.

class Driver
{
public void display()throws Exception
{
System.out.println("Display the Product specifications and the price!!!");
}

//Start of main method
public static void main (String[] args)throws Exception
{
// Scanner is used to get the input from the keyboard
Scanner stdIn = new Scanner(System.in);

Driver d; //object creation using parent class
char computer;
char a = 'y';
do
{
System.out.println("What kind of Computer would you like?");
System.out.println("a. Desktop");
System.out.println("b. Laptop");
System.out.println(" Enter option a or b:");
computer = stdIn.next().charAt(0);

// switch statement is added which will direct to the option specified by the user which
saves the time and easy to understand   
switch(computer)
{

//a or A it will take any of the input given by the user irrespective of upper or lower
case.
case 'a':
case 'A':
d= new Desktop();
d.display();
break;

case 'b':
case 'B':
d = new Laptop();
d.display();
break;

default:
System.out.println("invalid option. please type Y while asking for do you want to
continue and choose the correct option again!!!");
break;
}
System.out.println("Do you want to continue? (Y/N)");
a = stdIn.next().charAt(0);
} while (a == 'Y' || a == 'y');   
} //end of main method
} //end of parent class


// Details of Laptop are given in the following class
class Laptop extends Driver
{
String laptbrand,lapttype,laptcpubrand;
double laptcpuspeed,lapthddcap,laptramcap,laptdispsize;
double TotalPrice=0;
double price1,price2, price3, price4, price5, price6;

Scanner stdIn = new Scanner(System.in);
public Laptop()
{
// try block is used to check whether a error is there in the following code or not.
try
{
System.out.print("Which laptop brand would you like to prefer? ");
laptbrand = stdIn.next();
System.out.print("Enter the range of price you want the laptop brand to be: ");
price1 = stdIn.nextDouble();

System.out.print("Which brand of CPU do you prefer? ");
laptcpubrand = stdIn.next();
System.out.print("Enter the range of price you want the cpu brand to be: ");
price2 = stdIn.nextDouble();

System.out.print("How much CPU speed is required? ");
laptcpuspeed = stdIn.nextDouble();
System.out.print("What is the price you want for the CPU speed: ");
price3 = stdIn.nextDouble();

System.out.print("How much GB of HDD is required? ");
lapthddcap = stdIn.nextDouble();
System.out.print("Enter the price range for HDD: ");
price4 = stdIn.nextDouble();

System.out.print("How much GB of RAM is required? ");
laptramcap = stdIn.nextDouble();
System.out.print("Enter the price range for RAM: ");
price5 = stdIn.nextDouble();

System.out.print("How much laptop screen size(inches) do you prefer? ");
laptdispsize = stdIn.nextDouble();
System.out.print("Enter a price: ");
price6 = stdIn.nextDouble();
  
TotalPrice = price1 + price2 + price3 + price4 + price5 + price6;
} //try closed

// Always a try block should be followed by catch.

// Exception is a class which returns which kind of exception has occured
catch(Exception e)
{
System.out.println(e);
} //catch closed
} //constructor Laptop closed
public void display()
{
try
{
PrintStream stdout= new PrintStream("output.txt");
System.setOut(stdout);
stdout.println("Laptop brand: " + laptbrand);
stdout.println("CPU brand: " + laptcpubrand);
stdout.println("CPU speed: " + laptcpuspeed + "GHz");
stdout.println("HDD capacity: " + lapthddcap + "GB");
stdout.println("RAM capacity " + laptramcap + "GB");
stdout.println("Display size: "+ laptdispsize + "inches");
stdout.println("Total Price: " + TotalPrice + "$");
stdout.close();
}
catch(FileNotFoundException fx)
{
System.out.println(fx);
}
}
}

//Details of desktop are given in the following class
class Desktop extends Driver
{
String deskbrand,casetype,deskcpubrand;
double deskcpuspeed,deskhddcap,deskramcap,deskdispsize;
double TotalPrice=0;
double price1, price2, price3, price4, price5, price6, price7;

Scanner stdIn = new Scanner(System.in);

public Desktop(){
try
{
System.out.println("Which Desktop brand would you like to prefer? ");
deskbrand = stdIn.next();
System.out.println("Enter the range of price you want the desktop brand to be:");
price1 = stdIn.nextDouble();
  
System.out.println("What type of case would you like? Mini, Mid or Full Tower");
casetype = stdIn.next();
System.out.println("Enter the price range of case type: ");
price2 = stdIn.nextDouble();
  
System.out.println("Which brand of CPU do you prefer? ");
deskcpubrand = stdIn.next();
System.out.println("Enter the range of price you want the cpu brand to be: ");
price3 = stdIn.nextDouble();
  

System.out.println("How much CPU speed do you prefer? ");
deskcpuspeed = stdIn.nextDouble();
System.out.println("Enter the price range for the CPU speed: ");
price4 = stdIn.nextDouble();
  
System.out.println("How much GB of HDD do you prefer? ");
deskhddcap = stdIn.nextDouble();
System.out.println("Enter the price range of HDD: ");
price5 = stdIn.nextDouble();
  
System.out.println("How much GB of RAM is required? ");
deskramcap = stdIn.nextDouble();
System.out.println("Enter the price range for the RAM: ");
price6 = stdIn.nextDouble();
  
System.out.println("How much desktop screen size(inches) do you prefer? ");
deskdispsize = stdIn.nextDouble();
System.out.println("Enter a price: ");
price7 = stdIn.nextDouble();
  
TotalPrice = price1 + price2 + price3 + price4 + price5 + price6 + price7;
} //try closed
catch(Exception e)
{
System.out.println(e);
} //catch closed
} //constructor Desktop closed
public void display()
{
try
{
PrintStream stdout= new PrintStream("output.txt");
System.setOut(stdout);
stdout.println("Desktop brand: " + deskbrand);
stdout.println("Case type: " + casetype);
stdout.println("CPU brand: " + deskcpubrand);
stdout.println("CPU speed: " + deskcpuspeed);
stdout.println("HDD capacity: " + deskhddcap);
stdout.println("RAM capacity " + deskramcap);
stdout.println("Display size: "+ deskdispsize);
stdout.println("Total Price: " + TotalPrice + "$");
stdout.close();
}
catch(FileNotFoundException fx)
{
System.out.println(fx);
}
}

}

Edit: I have added polymorphism to the answer.

display function is written in the parent class.

and the display function is inherited in the sub-classes.

in previous code we have created objects for each class.

but since we are using polymorphism, i have created object only for parent class as Driver d;

and binded the same object to Laptop and Desktop dynamically and called display function. This is all about polymorphism.

Edit 2: Hi i have included redirecting to file.

In display function PrintStream class is used to write the console output to the file.

I know how to redirect the stdout to file but i dont know how to write both at a time in console and file.


Related Solutions

Write a try/catch/finally clause to catch one or more specific Exception objects in Java.
Write a try/catch/finally clause to catch one or more specific Exception objects in Java.
Java Modify subclass HourlyEmployee11 and class HourlyExc (created to hold the exception) to add a "try...
Java Modify subclass HourlyEmployee11 and class HourlyExc (created to hold the exception) to add a "try and catch" statement to catch an exception if "empStatus == 1" hourly wage is not between $15.00/hr. and $25.00/hr. The keywords “throw” and “throws” MUST be used correctly and both keywords can be used either in a constructor or in a method. If an exception is thrown, the program code should prompt the user for the valid input and read it in. *NOTE*- I...
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define...
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will enter...
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2....
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will...
Raising an Exception In the previous problem, you used a try/except statement to catch an exception....
Raising an Exception In the previous problem, you used a try/except statement to catch an exception. This problem deals with the opposite situation: raising an exception in the first place. One common situation in which you will want to raise an exception is where you need to indicate that some precondition that your code relies upon has not been met. (You may also see the assert statement used for this purpose, but we won’t cover that here.) Write a function...
What is Try and Catch in Java with example?
What is Try and Catch in Java with example?
This java program try to count all of the 1 at the rim of the block...
This java program try to count all of the 1 at the rim of the block of 1 surrounded by 0. The total of the count also includes all the 1 surrounded two pockets of 0 within the block. The correct answer fro the total count is 154. However, this program gives 167. Where is the fault of the program?    public class Cloture {     public static void main(String[] args) { int[][] carte = {                {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0},                {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0},...
I do not know how to: D. Apply exception handling using try-catch for System.OutOfMemoryException. the code...
I do not know how to: D. Apply exception handling using try-catch for System.OutOfMemoryException. the code i have in POWERSHELL: while($true) { $input= Read-Host "Enter the option 1-5" if ($input -eq 5) { break } #B. Create a “switch” statement that continues to prompt a user by doing each of the following activities, until a user presses key 5: switch ( $input ){ #Using a regular expression, list files within the Requirements1 folder, with the .log file extension and redirect...
PLease using C# Without using try-catch-throw for exception handling (Ch07), display an error message (using csc...
PLease using C# Without using try-catch-throw for exception handling (Ch07), display an error message (using csc or VS2017) when an input is invalid (i.e., no data, wrong format, wrong type, etc.) and fails the type conversion. Generate random integers from any of the following three non-overlapped ranges -14 ~ -7 -2 ~ 5 33 ~ 44 Numbers generated must also randomly distributed across the three ranges.
How does try/catch(exception) processing help resolve run time exceptions? What is a custom exception? What are...
How does try/catch(exception) processing help resolve run time exceptions? What is a custom exception? What are it's benefits? What does it mean when we raise a custom exception?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT