Download Part 3: Problems Solving Questions: 1) Add Java code at the

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Part 3: Problems Solving Questions:
1) Add Java code at the indicated location in the following class in order to read the first four lines
of a webpage (e.g. http://www.google.com), and write these four lines to a file stored on the
local hard drive (e.g. c:\test.txt). You need to handle any exceptions using a try..catch
statement so that if an exception is thrown, a simple error message is displayed. Assume
necessary libraries are imported.
(10 marks)
Hints: you may use
 readLine() method of the BufferedReader class.
 println() method of the PrintWriter class.
 openStream() method of the URL class.
public class WebReader {
private PrintWriter out;
private BufferedReader in;
private URL url;
public void read(){
//ADD CODE HERE!
}
public static void main(String[] args) {
WebReader wr = new WebReader();
wr.read();
}
}
try { (1 mark)
url = new URL("http://www.google.com"); (1 mark)
in = new BufferedReader(new InputStreamReader(url.openStream()));(1 mark)
out = new PrintWriter("c:/test.txt");(1 mark)
for (int i = 0; i < 4; i++)(1 mark)
out.println(in.readLine());(2 marks)
out.close(); in.close();(1 mark)
} catch (Exception ex) {(1 mark)
System.out.println("ERROR!"); (1 mark)
}
2) Add code to the following class so as to copy the contents of the ArrayList named places
to a file named c:\places.txt. Your answer should make use of the Iterator interface,
the ArrayList’s iterator() method, and the PrintWriter class. You should add
code at the indicated locations: at (1) to import java.io library, at (2) to declare
FileNotFoundException in the main method header, and at (3) to perform the copying
process.
(12 marks)
import java.util.*;
//(1)
public class CopyFile {
public static void main(String[] args){ //(2)
ArrayList<String> places = new ArrayList<String>(2);
places.add("Egypt");
places.add("Kuwait");
//(3)
}
}
Answer:
//(1)
import java.io.*; 1 mark
//(2)
public static void main(String[] args) throws FileNotFoundException {
2 marks
//(3)
PrintWriter out=new PrintWriter(new File("c:/places.txt"));3 marks
Iterator p = places.iterator(); 2 mark
while(p.hasNext()) 2 mark
out.println(p.next()); 1 mark
out.close();1 mark
3) Answer the following: (14 marks)
a) Develop a class Car to the following specification:
- The class has two private instance variables, String: brand and boolean: washed.
- The class has a zero-argument constructor that sets the values of brand and washed to
null and false respectively.
- The class has a 2-argument constructor that sets the values of brand and washed to
given values.
public class Car{1 mark
private String brand; 1 mark
private boolean washed; 1 mark
public Car() {1 mark
brand = null; 1 mark
washed = false; 1 mark
}
public Car(String b, boolean r) {1 mark
brand = b; 1 mark
washed = r; 1 mark
}
}
b) Develop an interface CarInterface that includes one method: public void
wash().
public interface CarInterface {1 mark
public void wash();1 mark
}
c) Modify your code in (a) so that the Car class implements CarInterface. The wash()
method should set the value of washed to true.
Note: You don’t need to rewrite the whole Car class again, but just the added or modified
code.
public class Car implements CarInterface {1 mark
...
...
public void wash() {1 mark
washed = true; 1 mark
}
}
4) Answer the following:
a) What is the output of the following code? Justify your answer.
public class Counter extends Thread {
private int num;
public Counter(int n) {
num = n;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.print(num);
try {
Thread.sleep(10);
} catch (InterruptedException ex) {}
}
}
public static void main(String[] args) {
Counter c1 = new Counter(1);
Counter c2 = new Counter(2);
c1.start();
c2.start();
}
}
The output would be something like the following: 1122211122
This output could be different (e.g. 1111122222, 1112211222, etc.)
Justification: No one thread had exclusive access to the CPU for its entire execution. It is not
the case that the threads take it in turns to run. One thread has access for a certain amount
of time and then another thread has access, and so on.
b) Modify the above class so that it uses alternative technique for creating threads. In your
answer, underline the changes you make in the above code.
public class Counter implements Runnable {
private int num;
public Counter(int n) {
num = n;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.print(num);
try {
Thread.sleep(10);
} catch (InterruptedException ex) {}
}
}
public static void main(String[] args) {
Counter c1 = new Counter(1);
Counter c2 = new Counter(2);
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c2);
t1.start();
t2.start();
}
}
5) Consider the following code:
import java.io.*;
import java.util.*;
public class RewriteCode {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("c:/text.txt"));
while(in.hasNextLine())
System.out.println("you wrote: " + in.nextLine());
}
}
Rewrite the above code according to the following:
a) Handle the IOException using try…catch clause instead of declaring it in the main
method header.
The program should display the message “I/O error!” if an IOException is thrown.
b) Replace the Scanner class with another class to read text from the text file. Make any
necessary changes to the code, and remove any unnecessary import statements.
import java.io.*;
import java.util.*;
public class RewriteCode {
public static void main(String[] args){ 1 mark (for not throwing IOException here)
try{1 mark
BufferedReader in =new BufferedReader(new FileReader("c:/text.txt"));2marks
String s = in.readLine();1 mark
while(s !=null){ 1 mark
System.out.println("you wrote" + s); 1 mark
s = in.readLine();1 mark
}
}catch(IOException e){ 1 mark
System.out.println("I/O error!"); 1 mark
}
}
}
6) Consider the following class Painter which is of the type Thread:
(10 marks)
import java.util.ArrayList;
public class Painter extends Thread{
//ADD CODE HERE FOR (a)
public Painter(String n){
setName(n);
//ADD CODE HERE FOR (b)
}
//ADD CODE HERE FOR (c)
public static void main(String[] args) {
//ADD CODE HERE FOR (d)
}
}
Add Java code at the locations indicated by the comments to do the following:
a) Create an ArrayList, named items, which will hold references to objects of the type
String.
b) Add two strings to items. For example, add "ceiling", and "floor".
c) Write a method that will be automatically invoked when we starting the Painter thread.
The method should print out all elements of items using for loop.
d) Create one instance of the Painter thread and start it.
Hints:
 you may use add(), get(), and size() methods of the ArrayList class
 you may use run() and start() methods of the Thread class.
a) 2 marks
ArrayList<String> items = new ArrayList<String>();
b) 2 marks
items.add("wall");
items.add("ceiling");
c) Total: 4 marks - any other for loop is acceptable (for example, if student used Iterator
interface).
public void run(){
for (int i = 0; i < items.size(); i++)
System.out.println(getName() + "'s painting " + items.get(i));
}
d) Total: 2 marks
Painter p1 = new Painter("Ahmed");
p1.start();
7) Consider the following class then answer the questions about it.
public class RaceCar extends Thread {
String model;
public RaceCar(String m) {model = m;}
public void run() {
for (int i = 0; i <= 5; i++) {
System.out.println(model + " is at location " + i);
try {
sleep(10);
} catch (Exception e) {}
}
}
}
a) Modify the above code so that uses the Runnable interface. Name the modified class
RaceCarRunnable. Underline the modified parts in your answer.
public class RaceCarRunnable implements Runnable{
String model;
public RaceCarRunnable(String m) {model = m;}
public void run() {
for (int i = 0; i <= 5; i++) {
System.out.println(model + " is currently at location " + i);
try {
Thread.sleep(10);
} catch (Exception e) {}
}
}
}
b) Write a class StartRace that has only a main method. In the main method, create two
RaceCar objects and start them.
public class StartRace {
public static void main(String[] args) {
RaceCar c1 = new RaceCar("Toyota");
RaceCar c2 = new RaceCar("Hodna");
c1.start();
c2.start();
}
}
c) Write a class StartRaceRunnable that has only a main method. In the main method,
create two RaceCarRunnable objects as threads and start them.
public class StartRaceRunnable {
public static void main(String[] args) {
RaceCarRunnable c1 = new RaceCarRunnable("Toyota");
RaceCarRunnable c2 = new RaceCarRunnable("Hodna");
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c2);
t1.start();
t2.start();
}
}
d) Briefly explain when should we inherit from the Thread class or implement the
Runnable interface when creating threads.
Defining threads by implementing the Runnable interface is used when you want to
inherent from a class other than the Thread class.
8) Consider the following code and answer the questions about it, assuming necessary libraries are
imported:(12 marks)
public class MyApplet extends JApplet {
JLabel label;
JTextField name;
JButton button;
public void init(){
setLayout(new FlowLayout());
label = new JLabel("What's your name?");
name = new JTextField(20);
button = new JButton("Greet");
add(label);
add(name);
add(button);
//(1)
}
private class Handler { //(2)
public void actionPerformed(ActionEvent e) {
//(3)
}
}
}
a) Draw the output of the above code if it is executed by the Java applet viewer.
b) What will happen if the setLayout statement is removed from the program? Justify your
answer (Hint: the default layout of a JApplet is the same as JFrame).
c) Add code at locations (1), (2) and (3) to create an ActionListener object and register it
with button.
When button is clicked, the program should show a greeting message to the user, for
example “Hello, Ahmed”, where ‘Ahmed’ is the text entered in name text field. Use
JOptionPane.showMessageDialog to display the greeting message.
a) 3 marks
(2 marks visual appearance of the elements – accuracy is not necessary, 1 mark for flow layout.
Don’t deduct marks for the size, title, or the labels “Applet” and “Applet started”).
b) 3 marks
The default layout, the border layout, would be used. Hence all visual elements will be
displayed on top of each other in the CENTER area by default.
c) 6 marks (2 marks x 3 statements)
at (1): button.addActionListener(new Handler());
at (2): implements ActionListener
at (3): JOptionPane.showMessageDialog(rootPane, "Hello " +
name.getText());
9) Consider the following code, and then answer the questions about it.
public class ExitDemo extends JFrame {
JButton exitButton;
JLabel infoLabel;
public ExitDemo() {
setSize(200, 100);
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
infoLabel = new JLabel("Press the exit button!");
exitButton = new JButton("Exit");
add(infoLabel, BorderLayout.NORTH);
add(exitButton, BorderLayout.SOUTH);
}
public static void main(String[] args) {
new ExitDemo().setVisible(true);
}
a) Draw (or describe) the result obtained when running the main method in the above class.
Your drawing doesn’t have to be of an accurate scale.
The drawing doesn’t have to be accurate. A simple drawing that shows how the GUI elements
are correctly distributed (the button is at the SOUTH and the label is at the NORTH) is good
enough.
b) Add java statements to the above code so that when the button exitButton is clicked,
the program displays the message “Goodbye!”, then the program is terminated. Use
method JOptionPane.showMessageDialog(null, “Goodbye”) to display the
goodbye message. In your answer, you don’t need to rewrite the above code again, but just
your added statements and their location.
add the following statement after line 9:
exitButton.addActionListener(new handleExit());
add the following statements after line 15
private class handleExit implements ActionListener{
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
10) Consider the following code and then answer the questions about it. (15 marks)
public class CarChoice {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
HashMap<Integer, String> carList;
carList = new HashMap<Integer, String>();
carList.put(1, "Toyota");
carList.put(2, "Ford");
carList.put(3, "Honda");
for (Integer idx : carList.keySet())
System.out.println(idx+"-"+carList.get(idx));
System.out.println("Which brand would you prefer?"+ "(enter a
number)");
try{
int br = in.nextInt();
if (carList.containsKey(br))
System.out.println(carList.get(br) + " is a nice brand.");
else
System.out.println("Wrong brand number!");
}catch(InputMismatchException e){
System.out.println("Error! Not a number!");
}
}
}
a) What will be displayed on the screen once the code is executed?
1 - Toyota
2 - Ford
3 - Honda
Which brand would you prefer? (enter a number)
b) What will be the output if the user enters the following values:
i. 1
Toyota is a nice brand.
ii. 4
Wrong brand number!
iii. e
Error! This is not a number!
Note: The method containsKey()in the code above returns true if the HashMap
contains a mapping for the specified key, and false otherwise.
c) Give an example from the code about the use of defensive programming, and another
example about exception handling.
Example of defensive programming: “if..else..” statement is used to check that the
use entered a correct number.
Example of exception handling: “try..catch..” statement is used to check that the
user entered numeric value.
11) Develop a class Player to the following specification:
 The class has two private instance variables, String: name and int: age.
 The class has a zero-argument constructor that sets the values of name and age to null
and 0 respectively.
 The class has a two-argument constructor that sets the values of name and age to given
values.
public class Player {
private String name;
private int age;
public Player() {
name = null;
age = 0;
}
public Player(String n, int a) {
name = n;
age = a;
}
}
12) Develop a class SimpleClient for a client according to the following specification:
 The class has two private instance variables: socket of type Socket, and fromServer
of type BufferedReader.
 The class has a public method start() that connects to a server with the ip address
127.0.0.1 and port 3500, and then prints out one message received from the server. After
printing, the input stream and the socket should be closed.
Note that checked exceptions should be caught and handled by showing appropriate error
message. You don’t need to write any import statements.
public class SimpleClient {
Socket socket;
BufferedReader fromServer;
public void start(){
try{
socket = new Socket("127.0.0.1", 3500);
fromServer = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
System.out.println(fromServer.readLine());
fromServer.close();
socket.close();
} catch (IOException e){System.out.println("Error in the
connection!");}
}
}
13) Develop 3 classes Shape, Circle, and Rectangle according to the following specifications:
(20 marks)
The class hierarchy:
The Shape class has:
 a public instance variables, String color.
 a private class variable noOfShapes to store the number of created Shape objects.
 a one-argument constructor that sets the values of color to a given value, and
increments noOfShapes by 1.
 a static method getNoOfShapes() that returns the number of created Shape
objects.
The Rectangle class has:
 two public instance variables int height and int width.
 a three-argument constructor that sets the values of color, height and width to
given values.
The Circle class has:
 a public instance variable, int radius.
 a two-argument constructor that sets the values of color and radius to given
values.
 a public method toString() that returns a string consisting of the circle’s color and
radius; for example, “Color: Red, Radius: 10”.
public class Shape {
public String color;
private static int noOfShapes;
public Shape(String clr) {
color = clr;
noOfShapes++;
}
public static int getNoOfShapes() {
return noOfShapes;
}
}
public class Rectangle extends Shape{
public int height, width;
public Rectangle(String clr, int h, int w) {
super(clr);
height = h;
width = w;
}
}
public class Circle extends Shape{
public int radius;
public Circle(String clr, int rad) {
super(clr);
radius = rad;
}
public String toString(){
return "Color: " + color + ", Radius: " + radius;
}
}
14) Re-write the following code using if-else statement:
char c;
...
switch(c){
case 'y':
case 'Y':
System.out.println("Yes");
break;
case 'n':
case 'N':
System.out.println("No");
break;
default:
System.out.println("Wrong answer!");
}
char c;
...
if(c=='y' || c=='Y')
System.out.println("Yes");
else if(c=='n' || c=='N')
System.out.println("No");
else
System.out.println("Wrong answer!");
15) Re-write the following code using StringBuffer instead of String, and for instead of
while:
(10 marks)
String[] names = new String[5];
int i = 0;
while(i < names.length){
names[i] = "";
i++;
}
StringBuffer[] names = new StringBuffer[5];
for(int i = 0; i < names.length; i++){
names[i] = new StringBuffer("");
}
16) The following class represents a client program that when instantiated and run should send a
message, “Hello from a client”, to a server program. The server is located at IP address:
127.0.0.1 and PORT#:3000. Complete the code where indicated to achieve the above scenario
(Hint: a minimum of 5 statements should be added). Assume all required libraries are imported.
(9 marks)
public class client {
private Socket socket;
private PrintWriter toServer;
public void run() {
try {
//add code here!
} catch (Exception e) {}
}
}
socket = new Socket("127.0.0.1", 3000); 2marks
toServer = new PrintWriter(socket.getOutputStream(),true); 2marks
toServer.println("Hello from a client!"); 2marks
toServer.close();1.5mark
socket.close();1.5mark
17) The following code represents a skeleton of the class MyFrame. An illustration is given beside
the code to show the design of MyFrame. Clicking the “Bigger” (or “Smaller”) button will result
in increasing (or decreasing) the size of the black square in the middle of the illustration. In
order to implement this in Java, a variable named length should be incremented (or
decremented) whenever “Bigger” (or “Smaller”) button is clicked, and then the square should be
re-painted again using the updated value of length. (19 marks)
In this question, you are required complete the code skeleton at the indicated locations
according to the following:
a) Add code at (a) in order to
 Match the shown design.
 Initialize length to the value of 50.
 Attach both buttons (Bigger and Smaller) to an event listener of the type MyHandler
(see the code below).
b) Add code at (b) in order to implement the paint method, which will include the code to
draw the black square.
Hint: you may use the method fillRect(x, y, width, height) of the Graphics
class.
c) Add code at (c) in order to check which button is clicked and change the value of length
accordingly; and then call an appropriate method to redraw the black square.
Hint: you may use the method getSource() of the ActionEvent class.
public class MyFrame extends JFrame{
private int length;
private JButton increase, decrease;
public MyFrame() {
//(a)
}
//(b)
private class MyHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//(c)
}
}
public static void main(String[] args){
MyFrame f = new MyFrame();
f.setVisible(true);
}
}
(a) Total: 10 marks
setTitle("test");(4 marks for properly setting JFrame attributes)
setSize(200, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
length = 50; (1 mark)
increase = new JButton("Bigger");(3 marks for creating buttons and adding them)
decrease = new JButton("Smaller");
add(decrease); add(increase);
increase.addActionListener(new MyHandler());(1 mark)
decrease.addActionListener(new MyHandler());(1 mark)
(b) Total: 4 marks
public void paint(Graphics g) {(1 mark)
super.paint(g); (1 mark)
g.fillRect(50,80 , length, length); (2 marks)
}
(c) Total: 5 marks
if (e.getSource() == increase) (2 marks)
length += 10; (1 mark)
else (don’t deduct marks if two “if” statements are used instead of using if..else)
length -= 10; (1 mark)
repaint();(1 mark)
18) When running the following code, the GUIdisplays a window that includes two questions with
two possible answers: “True” and “False”. For each question, the user should choose either true
or false.
(17 marks)
public class GUI extends JFrame{
JLabel q1, q2;
JRadioButton q1True, q1False, q2True, q2False;
JButton result;
//(1)
public GUI() {
setSize(250, 140);
setLayout(new FlowLayout());
// (2)
q1 = new JLabel("q1. 5 + 5 = 10 ?");
q2 = new JLabel("q2. 9 - 6 = 7 ?");
q1True = new JRadioButton("True");
q1False = new JRadioButton("False");
q2True = new JRadioButton("True");
q2False = new JRadioButton("False");
result = new JButton("Evaluate");
//(3)
add(q1); add(q1True); add(q1False);
add(q2); add(q2True); add(q2False);
add(result);
}
//(4)
public static void main(String[] args) {
new GUI().setVisible(true);
}
}
a) Draw the output of the above code.
4 marks ( 0.5 for no title, 0.5 for size, 1 for flowlayout, and 2 for correct visual elements)
Answer:
b) In the above code, clicking on the close window icon does not end the program, but only
closes the window. Add code at location (2) to fix this problem.
add at (2) the following statement:
setDefaultCloseOperation(EXIT_ON_CLOSE); 1 marks
c) There is a bug in above code: a user is able to choose both “True” and “False” choices at the
same time. Add code at locations (1) and (3) to fix this bug.
add at (1)
ButtonGroup q1Group, q2Group; 1 marks
and add at (3)
q1Group = new ButtonGroup(); 1 mark
q1Group.add(q1True); 0.5 mark
q1Group.add(q1False); 0.5 mark
q2Group = new ButtonGroup(); 1 mark
q2Group.add(q2True); 0.5 mark
q2Group.add(q2False); 0.5 mark
d) Add code at locations (3) and (4) to create an ActionListener object and register it
with the result button. When the result button is clicked, the program should display
“Correct” if the user correctly answered the two questions, and “False” otherwise. Use the
statement JOptionPane.showMessageDialog(null, “Correct”) to display
“Correct”, and a similar statement to display “Wrong”.
add at (3)
result.addActionListener(new MyHandler()); 2 marks
and at (4)
private class MyHandler implements ActionListener{ 1 marks
public void actionPerformed(ActionEvent e) { 1 marks
if(q1True.isSelected() && q2False.isSelected())1 marks
JOptionPane.showMessageDialog(null, "Correct!"); 1 mark
else
JOptionPane.showMessageDialog(null, "Wrong!"); 1 mark
}
}
19) Write a class named Greeting that has only a main method. In the main method, ask the user
to enter his/her name and then display a greeting message (e.g. “Hello Ahmed”). Use the
Scanner class to read the input. Import any necessary java libraries.
import java.util.Scanner;
public class Greeting {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name:");
System.out.println("Hello " + sc.nextLine());
}
}
20) Write a Java program according to the following specifications:
a) Develop an interface AnimalInterface that includes one method: public void
grow(int a). Later when grow(int a) is implemented in a class, it should increment the
age of the animal by the value of a.
b) Develop a public abstract class Animal to the following specification:
 The class implements AnimalInterface.
 The class has one private instance variable int age.
 The class has accessor and mutator methods for the variable age.
 The class includes implementation of any further mandatory method(s).
c) Develop a public class Bird to the following specification:
 The class is a subclass of Animal.
 The class has a private instance variable boolean canFly.
 The class has a two-argument constructor to set the its instance variables to given
values.
 The class overrides toString() in java.lang.Object to return a string
representation of the values of the instance variables as in the following example (the
italic text represents the variables’ values): Bird's age: 2. Can it fly? true
d) Develop a public class Fish to the following specifications:
 The class is a subclass of Animal.
 The class has a private instance variable features of the type
ArrayList<String>.
 The class has a one argument constructor to set the fish’s age to a given value and
instantiate features.
 The class has two public methods addFeature(String f) and
removeFeatures(String f) to add or remove a feature f to features.
(a)
public interface AnimalInterface { 1.5 mark
public void grow(int a); 1.5 mark (give only 0.5 mark if not abstract, i.e. if the method
contains a body within braces)
}
(b)
public abstract class Animal implements AnimalInterface{ 1.5 mark
private int age; 1 mark
public int getAge() {return age;} 1.5 mark
public void setAge(int a){age = a;} 1.5 mark
public void grow(int a) {age += a;} 1.5 mark
}
(c)
public class Bird extends Animal{ 1 mark
private boolean canFly; 1 mark
public Bird(int age, boolean cf) { 2 marks
canFly = cf;
setAge(age);
}
public String toString(){2 marks
return "Bird's age: " + getAge() + ". Can it fly? " + canFly;
}
}
(d)
public class Fish extends Animal{ 1 mark
private ArrayList<String> features; 1 mark
public Fish(int age) { 2 marks
setAge(age);
features = new ArrayList<String>();
}
public void addFeature(String s){ 2 marks
features.add(s);
}
public void removeFeature(String s){ 2 marks
features.remove(s);
}
}
21) Write a Java program according to the following specifications: (16 marks)
a) Develop a public interface VehicleInterface that includes two methods: public
void move() and public void stop(). Later when these methods are
implemented: stop() should set the value of a variable named speed to 0 , while
move() should set speed to a value greater than zero.
b) Develop a public abstract class Vehicle to the following specification:
 The class implements VehicleInterface.
 The class has one private static variable int counter that is initialized to 0. The
variable counter should be incremented by 1 whenever an object of the type
Vehicle is created.
 The class has one public instance variable int speed.
 The class has an accessor method for the variable counter.
 The class includes implementation of the method stop() only.
c) Develop a public class Car to the following specification:
 The class is a subclass of Vehicle.
 The class includes implementation of the method move() which sets speed to 100.
a) Total: 3 marks (1 mark per LOC)
public interface VehicleInterface {
public void move();
public void stop();
}
b) Total: 10 marks (1 mark per LOC, except the first LOC which worth 2 marks)
public abstract class Vehicle implements VehicleInterface{
public static int counter = 0;
public int speed;
public Vehicle() {
counter++;
}
public int getCounter() {
return counter;
}
public void stop() {
speed = 0;
}
}
c) Total: 3 marks
public class Car extends Vehicle{
public void move() {
speed = 100;
}
}
22) Write a temperature conversion program that converts from Celsius to Fahrenheit. The Celsius
temperature should be entered from the keyboard (via a JTextField). A JLabel should be
used to display the converted temperature.
Your program should have an interface similar to the following one:
Your interface should have the following characteristics/behaviors:

Title: “Temp Conversion”

Size: 250 x 100

Layout manager: FlowLayout

The program is terminated when the „x‟ button is pressed.
package MTA;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TempConversion extends JFrame{
JButton toFeh;
JTextField cel;
JLabel result;
public TempConversion() {
//frame properties
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Temp Conversion");
setSize(250, 100);
setLayout(new FlowLayout());
//creating gui elements
toFeh = new JButton("Covert to Fahrenheit");
cel = new JTextField(10);
result = new JLabel(" ");
//adding gui elements
add(cel);
add(result);
add(toFeh);
//add events
}
public static void main(String[] args) {
new TempConversion().setVisible(true);
}
}
23) Write Java code that will ask the user to enter an address of a webpage, and then displays only
the first line of the contents of that webpage. You don’t need to write a complete class, import
any libraries, or handle any exceptions.
In your answer, use the following classes: BufferedReader, InputStreamReader, and
URL. Also, you may use the following methods: readLine() from the BufferedReader
class, and openStream() from the URL class.
(12 marks)
System.out.println("Enter a web address (e.g. www.google.com):"); 1 mark
BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in)); 2 marks
String address = "http://" + fromUser.readLine(); 2 marks
URL url = new URL(address); 2 marks
BufferedReader fromWeb = new BufferedReader(new InputStreamReader(url.openStream()));2 marks
System.out.println(fromWeb.readLine());2 marks
fromUser.close();0.5 mark
fromWeb.close();0.5 mark
Note to the tutors: don’t deduct marks if the student does any of the following:(i) used the Scanner class to get input from the user,
(ii) printed the whole contents of the webpage.
24) Write Java code to copy the first line of text from the file “c:\input.txt” and to the file
“c:\output.txt”. Use the BufferedReader class to read the input, and the PrintWriter
class to write the output.
(10 marks)
BufferedReader in = new BufferedReader(new FileReader("c:/input.txt"));
PrintWriter out = new PrintWriter(new File("c:/output.txt"));
out.write(in.readLine());
out.close();
in.close();
25) Write Java code to read a line of text from the user and then display it. Use the BufferedReader
class to read the input.
BufferedReader stdin = new BufferedReader(new Input streamReader (system.in));
String s = stdin.readLine();
System.out.println(s);
Stdin.close();