Write a Java program that contains two classes: Computer and Laptop. Both classe
ID: 3583644 • Letter: W
Question
Write a Java program that contains two classes: Computer and Laptop. Both classes have their own constructors and a method. In main method we create object of two classes and call their methods. Write a program that creates a user interface to perform integer divisions. The user enters two numbers in the textfields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a NumberFormatException. If Num2 were Zero, the program would throw an ArithmeticException Display the exception in a message dialog box. Show output screen for all exception mentioned above.Explanation / Answer
Ans.1.
import java.util.*;
import java.lang.*;
import java.io.*;
class Laptop
{
String color;
int price;
Laptop(String color_, int price_)
{
color = color_;
price = price_;
}
void showDetails()
{
System.out.println("The color of laptop is: ", color, " and price is: ", price);
}
}
class Computer
{
String color;
int price;
Computer(String color_, int price_)
{
color = color_;
price = price_;
}
void showDetails()
{
System.out.println("The color of computer is: ", color, " and price is: ", price);
}
}
public static void main (String[] args)
{
Laptop laptop1 = new Laptop("black", 40000);
Computer computer1 - new Computer("white", 30000);
laptop1.showDetails();
computer1.showDetails();
}
Ans.2. /* package whatever; // don't place package name! */
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
public class Division extends Applet implements Operation
{
TextField num1, num2, result;
Button b;
Label first;
public void init()
{
first = new Label("Enter numbers to divide");
num1 = new TextField("",5);
num2 = new TextField("",5);
result =new TextField("",5);
b = new Button("Divide");
add(first);
add(num1);
add(num2);
add(b);
add(result);
b.addOperation(this);
}
public void actionPerformed(Division d)
{
if(d.getActionCommand()=="Divide")
{
try
{
int a = Integer.parseInt(num1.getText());
int b = Integer.parseInt(num2.getText());
int answer = a/b;
result.setText(answer);
}
catch(ArithmeticException e1)
{
JOptionPane.showMessageDialog(null,"Arthimetic Exception");
}
catch(NumberFormatException e2)
{
JOptionPane.showMessageDialog(null,"NumberFormatException");
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.