1. Develop Rational number class in Java. Use JavaDoc comments for documentation. Your implementation should use efficient representation for a rational number, i.e. (500 / 1000) should be represented as (½). import java.util.Scanner; public class Rational { /** * The Numerator part of Rational */ private int numerator; /** * The Denominator part of Rational */ private int denominator; /** * create and initialize a new Rational object */ public Rational(int numerator, int denominator) { if (denominator == 0) { throw new RuntimeException("Denominator is zero"); } int g = gcd(numerator, denominator); if (g == 1) { System.out.println("No Common Divisor for Numerator and Denominator"); this.numerator = numerator; this.denominator = denominator; } else { this.numerator = numerator / g; this.denominator = denominator / g; } } /**
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
1. Develop Rational number class in Java. Use JavaDoc comments for documentation. Your implementation should use efficient representation for a rational number, i.e. (500 / 1000) should be represented as (½).
import java.util.Scanner;public class Rational { /** * The Numerator part of Rational */
private int numerator; /** * The Denominator part of Rational */
private int denominator; /** * create and initialize a new Rational object */ public Rational(int numerator, int denominator) { if (denominator == 0) { throw new RuntimeException("Denominator is zero"); } int g = gcd(numerator, denominator); if (g == 1) { System.out.println("No Common Divisor for Numerator and Denominator"); this.numerator = numerator; this.denominator = denominator; } else { this.numerator = numerator / g; this.denominator = denominator / g; }
}
/** * return string representation of (this) */ public String toString() { return numerator + "/" + denominator; }
/** *
* @param m * @param n * @return Greatest common divisor for m and n */ private static int gcd(int m, int n) { if (0 == n) return m; else return gcd(n, m % n); }
/************************************************************************* * Test client *************************************************************************/
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter Numerator : "); int numerator = scanner.nextInt(); System.out.print("Enter Denominator : "); int denominator = scanner.nextInt(); Rational rational; rational = new Rational(numerator, denominator); System.out.println("Efficient Representation for the rational number :" + rational);
}
}
2. Develop Date class in Java similar to the one available in java.util package. Use JavaDoc comments.
import java.util.*;
public class Datedemo
{ public static void main(String args[])
{
/* Create date object with current date and time. */
Date date = new Date(); System.out.println("Today is " + date); } }
3. Implement Lisp-like list in Java. Write basic operations such as 'car', 'cdr', and 'cons'. If L is a list [3, 0, 2, 5], L.car() returns 3, while L.cdr() returns [0,2,5].
class Twowheeler extends Vehicle{int noofwheel;Twowheeler(String r,int m,int n){super(r,m);noofwheel=n;}void display(){System.out.println("Two wheeler tvs");super.display();System.out.println("no of wheel" +noofwheel);}}
class Threewheeler extends Vehicle{int noofleaf;Threewheeler(String r,int m,int n){super(r,m);noofleaf=n;}void display(){
System.out.println("three wheeler auto");super.display();System.out.println("no of leaf" +noofleaf);}}
class Fourwheeler extends Vehicle{int noofleaf;Fourwheeler(String r,int m,int n){super(r,m);noofleaf=n;}void display(){System.out.println("four wheeler car");super.display();System.out.println("no of leaf" +noofleaf);}}
public class Vehicledemo{public static void main(String arg[]){Twowheeler t1;Threewheeler th1;Fourwheeler f1;t1=new Twowheeler("TN74 12345", 1,2);th1=new Threewheeler("TN74 54321", 4,3);f1=new Fourwheeler("TN34 45677",5,4);t1.display();th1.display();f1.display();}}
6. Design classes for Currency, Rupee, and Dollar. Write a program that randomly generates Rupee and Dollar objects and write them into a file using object serialization. Write another program to read that file, convert to Rupee if it reads a Dollar, while leave the value as it is if it reads a Rupee.
import java.io.Serializable;
public abstract class Currency implements Serializable {
protected static final Double DOLLAR_RUPEE_EXCHAGERATE = 44.445D;
public Currency(Double money) {super();this.money = money;
}
protected Double money;
public abstract Double getValue ();
public abstract String getPrintableValue();
}
/** * * @author Jana * */public class Rupee extends Currency {
7. Design a scientific calculator using event-driven programming paradigm of Java.
import java.awt.*;import java.awt.event.*; // class CalcFrame for creating a calcul // ator frame and added windolistener to // close the calculator
class CalcFrame extends Frame {
CalcFrame( String str) { // call to superclass super(str); // to close the calculator(Frame)
addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent we) { System.exit(0); }
});
}
}
// main class Calculator implemnets two // interfaces ActionListener // and ItemListener
public class Calculator implements ActionListener, ItemListener { // creating instances of objects CalcFrame fr; MenuBar mb; Menu view, font, about; MenuItem bold, regular, author; CheckboxMenuItem basic, scientific; CheckboxGroup cbg;
Checkbox radians, degrees; TextField display; Button key[] = new Button[20]; // creates a button object array of 20 Button clearAll, clearEntry, round;Button scientificKey[] = new Button[10]; // creates a button array of 8 // declaring variablesboolean addButtonPressed, subtractButtonPressed, multiplyButtonPressed;boolean divideButtonPressed, decimalPointPressed, powerButtonPressed;boolean roundButtonPressed = false;double initialNumber;// the first number for the two number operationdouble currentNumber = 0;//the number shown in the screen while it is //being pressedint decimalPlaces = 0; // main function
public static void main (String args[]) { // constructor Calculator calc = new Calculator(); calc.makeCalculator(); }
public void makeCalculator() { // size of the button final int BWIDTH = 25; final int BHEIGHT = 25; int count =1; // create frame for the calculator fr = new CalcFrame("Basic Calculator"); // set the size fr.setSize(200,270); fr.setBackground(Color.blue);; // create a menubar for the frame mb = new MenuBar(); // add menu the menubar view = new Menu("View"); font = new Menu ("Font"); about = new Menu("About"); // create instance of object for View me // nu basic = new CheckboxMenuItem("Basic",true); // add a listener to receive item events // when the state of an item changes basic.addItemListener(this); scientific = new CheckboxMenuItem("Scientific");
// add a listener to receive item events // when the state of an item changes scientific.addItemListener(this); // create instance of object for font me // nu bold = new MenuItem("Arial Bold"); bold.addActionListener(this); regular = new MenuItem("Arial Regular"); regular.addActionListener(this); // for about menu author = new MenuItem("Author"); author.addActionListener(this); // add the items in the menu view.add(basic); view.add(scientific); font.add(bold); font.add(regular); about.add(author); // add the menus in the menubar mb.add(view); mb.add(font); mb.add(about); // add menubar to the frame fr.setMenuBar(mb); // override the layout manager fr.setLayout(null); // set the initial numbers that is 1 to // 9
for (int row = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col) { // this will set the key from 1 to 9 key[count] = new Button(Integer.toString(count)); key[count].addActionListener(this); // set the boundry for the keys key[count].setBounds(30*(col + 1), 30*(row + 4),BWIDTH,BHEIGHT); key[count].setBackground(Color.yellow); // add to the frame fr.add(key[count++]); }
}
// Now create, addlistener and add to fr // ame all other keys //0 key[0] = new Button("0"); key[0].addActionListener(this); key[0].setBounds(30,210,BWIDTH,BHEIGHT); key[0].setBackground(Color.yellow); fr.add(key[0]); //decimal key[10] = new Button("."); key[10].addActionListener(this); key[10].setBounds(60,210,BWIDTH,BHEIGHT); key[10].setBackground(Color.yellow); fr.add(key[10]); //equals to key[11] = new Button("="); key[11].addActionListener(this); key[11].setBounds(90,210,BWIDTH,BHEIGHT); key[11].setBackground(Color.yellow); fr.add(key[11]); //multiply key[12] = new Button("*"); key[12].addActionListener(this); key[12].setBounds(120,120,BWIDTH,BHEIGHT); key[12].setBackground(Color.yellow); fr.add(key[12]); //divide key[13] = new Button("/"); key[13].addActionListener(this); key[13].setBounds(120,150,BWIDTH,BHEIGHT); key[13].setBackground(Color.yellow); fr.add(key[13]); //addition key[14] = new Button("+"); key[14].addActionListener(this); key[14].setBounds(120,180,BWIDTH,BHEIGHT); key[14].setBackground(Color.yellow); fr.add(key[14]); //subtract key[15] = new Button("-"); key[15].addActionListener(this); key[15].setBounds(120,210,BWIDTH,BHEIGHT); key[15].setBackground(Color.yellow); fr.add(key[15]); //reciprocal key[16] = new Button("1/x");
key[16].addActionListener(this); key[16].setBounds(150,120,BWIDTH,BHEIGHT); key[16].setBackground(Color.yellow); fr.add(key[16]); //power key[17] = new Button("x^n"); key[17].addActionListener(this); key[17].setBounds(150,150,BWIDTH,BHEIGHT); key[17].setBackground(Color.yellow); fr.add(key[17]); //change sign key[18] = new Button("+/-"); key[18].addActionListener(this); key[18].setBounds(150,180,BWIDTH,BHEIGHT); key[18].setBackground(Color.yellow); fr.add(key[18]); //factorial key[19] = new Button("x!"); key[19].addActionListener(this); key[19].setBounds(150,210,BWIDTH,BHEIGHT); key[19].setBackground(Color.yellow); fr.add(key[19]); // CA clearAll = new Button("CA"); clearAll.addActionListener(this); clearAll.setBounds(30, 240, BWIDTH+20, BHEIGHT); clearAll.setBackground(Color.yellow); fr.add(clearAll); // CE clearEntry = new Button("CE"); clearEntry.addActionListener(this); clearEntry.setBounds(80, 240, BWIDTH+20, BHEIGHT); clearEntry.setBackground(Color.yellow); fr.add(clearEntry); // round round = new Button("Round"); round.addActionListener(this); round.setBounds(130, 240, BWIDTH+20, BHEIGHT); round.setBackground(Color.yellow); fr.add(round); // set display area display = new TextField("0"); display.setBounds(30,90,150,20); display.setBackground(Color.white); // key for scientific calculator // Sine
scientificKey[6].setVisible(false); fr.add(scientificKey[6]); // E scientificKey[7] = new Button("E"); scientificKey[7].addActionListener(this); scientificKey[7].setBounds(220, 210, BWIDTH + 10, BHEIGHT); scientificKey[7].setBackground(Color.yellow); scientificKey[7].setVisible(false); fr.add(scientificKey[7]); // to degrees scientificKey[8] = new Button("todeg"); scientificKey[8].addActionListener(this); scientificKey[8].setBounds(180, 240, BWIDTH + 10, BHEIGHT); scientificKey[8].setBackground(Color.yellow); scientificKey[8].setVisible(false); fr.add(scientificKey[8]); // to radians scientificKey[9] = new Button("torad"); scientificKey[9].addActionListener(this); scientificKey[9].setBounds(220, 240, BWIDTH + 10, BHEIGHT); scientificKey[9].setBackground(Color.yellow); scientificKey[9].setVisible(false); fr.add(scientificKey[9]); cbg = new CheckboxGroup(); degrees = new Checkbox("Degrees", cbg, true); radians = new Checkbox("Radians", cbg, false); degrees.addItemListener(this); radians.addItemListener(this); degrees.setBounds(185, 75, 3 * BWIDTH, BHEIGHT); radians.setBounds(185, 95, 3 * BWIDTH, BHEIGHT); degrees.setVisible(false); radians.setVisible(false); fr.add(degrees); fr.add(radians); fr.add(display); fr.setVisible(true); } // end of makeCalculator
public void actionPerformed(ActionEvent ae) { String buttonText = ae.getActionCommand(); double displayNumber = Double.valueOf(display.getText()).doubleValue(); // if the button pressed text is 0 to 9
// this will convert the numbers display // ed to degrees if (buttonText == "todeg") display.setText(Double.toString(Math.toDegrees(displayNumber))); // this will convert the numbers display // ed to radians if (buttonText == "torad") display.setText(Double.toString(Math.toRadians(displayNumber)));
if (buttonText == "=") { currentNumber = 0; // if add button is pressed if(addButtonPressed) display.setText(Double.toString(initialNumber + displayNumber)); // if subtract button is pressed if(subtractButtonPressed) display.setText(Double.toString(initialNumber - displayNumber)); // if divide button is pressed
if (divideButtonPressed) { // check if the divisor is zero
if(displayNumber == 0) { MessageBox mb = new MessageBox ( fr, "Error ", true, "Cannot divide by zero."); mb.show(); }
// if multiply button is pressed if(multiplyButtonPressed) display.setText(Double.toString(initialNumber * displayNumber)); // if power button is pressed if (powerButtonPressed) display.setText(power(initialNumber, displayNumber)); // set all the buttons to false resetAllButtons(); }
if (buttonText == "Arial Regular") { for (int i =0; i < 10; ++i) key[i].setFont(new Font("Arial", Font.PLAIN, 12)); }
if (buttonText == "Arial Bold") { for (int i =0; i < 10; ++i) key[i].setFont(new Font("Arial", Font.BOLD, 12)); }
if (buttonText == "Author") {MessageBox mb = new MessageBox ( fr, "Calculator ver 1.0 beta ", true, "Author: Inder Mohan Singh."); mb.show(); }
} // end of action events
public void itemStateChanged(ItemEvent ie) {
if (ie.getItem() == "Basic") { basic.setState(true); scientific.setState(false); fr.setTitle("Basic Calculator"); fr.setSize(200,270); // check if the scientific keys are visi // ble. if true hide them
if (scientificKey[0].isVisible()) { for (int i=0; i < 8; ++i) scientificKey[i].setVisible(false); radians.setVisible(false); degrees.setVisible(false); }
}
if (ie.getItem() == "Scientific") { basic.setState(false); scientific.setState(true); fr.setTitle("Scientific Calculator"); fr.setSize(270,270); // check if the scientific keys are visi // ble. if true display them
if (!scientificKey[0].isVisible()) { for (int i=0; i < 10; ++i) scientificKey[i].setVisible(true); radians.setVisible(true); degrees.setVisible(true); }
}
} // end of itemState
// this method will reset all the button // Pressed property to false
9. Develop a simple OPAC system for library using even-driven and concurrent programming paradigms of Java. Use JDBC to connect to a back-end database.
Event driven
import java.sql.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Datas extends JFrame implements ActionListener {
super("Our Application");Container c = getContentPane();c.setLayout(new GridLayout(5,1));id = new JTextField(20);name = new JTextField(20);next = new JButton("Next BOOK");p = new JPanel();c.add(new JLabel("ISBN",JLabel.CENTER));c.add(id);
public static void main(String arg[]){Ja j=new Ja();j.myput();}}
10. Develop multi-threaded echo server and a corresponding GUI client in Java.
import java.net.*; import java.io.*;
public class EchoServer { ServerSocket m_ServerSocket; public EchoServer() { try { // Create the server socket. m_ServerSocket = new ServerSocket(12111); } catch(IOException ioe) { System.out.println("Could not create server socket at 12111. Quitting."); System.exit(-1); } System.out.println("Listening for clients....."); // Successfully created Server Socket. Now wait for connections. int id = 0; while(true) { try { // Accept incoming connections. Socket clientSocket = m_ServerSocket.accept(); // accept() will block until a client connects to the server. // If execution reaches this point, then it means that a client // socket has been accepted. // For each client, we will start a service thread to // service the client requests. This is to demonstrate a // multithreaded server, although not required for such a // trivial application. Starting a thread also lets our // EchoServer accept multiple connections simultaneously.
// Start a service thread ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++); cliThread.start(); } catch(IOException ioe) { System.out.println("Exception encountered on accept. Ignoring. Stack Trace :"); ioe.printStackTrace(); } } } public static void main (String[] args) { new EchoServer(); } class ClientServiceThread extends Thread { Socket m_clientSocket; int m_clientID = -1; boolean m_bRunThread = true; ClientServiceThread(Socket s, int clientID) { m_clientSocket = s; m_clientID = clientID; } public void run() { // Obtain the input stream and the output stream for the socket // A good practice is to encapsulate them with a BufferedReader // and a PrintWriter as shown below. BufferedReader in = null; PrintWriter out = null; // Print out details of this connection System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " + m_clientSocket.getInetAddress().getHostName()); try {
in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream())); out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream())); // At this point, we can read for input and reply with appropriate output. // Run in a loop until m_bRunThread is set to false while(m_bRunThread) { // read incoming stream String clientCommand = in.readLine(); System.out.println("Client Says :" + clientCommand); if(clientCommand.equalsIgnoreCase("quit")) { // Special command. Quit this thread m_bRunThread = false; System.out.print("Stopping client thread for client : " + m_clientID); } else { // Echo it back to the client. out.println(clientCommand); out.flush(); } } } catch(Exception e) { e.printStackTrace(); } finally { // Clean up try { in.close(); out.close(); m_clientSocket.close(); System.out.println("...Stopped"); } catch(IOException ioe) {
ioe.printStackTrace(); } } } } }
import java.net.*; import java.io.*;
// A client for our multithreaded EchoServer. public class EchoClient { public static void main(String[] args) { // First parameter has to be machine name if(args.length == 0) { System.out.println("Usage : EchoClient <serverName>"); return; } Socket s = null; // Create the socket connection to the EchoServer. try { s = new Socket(args[0], 12111); } catch(UnknownHostException uhe) { // Host unreachable System.out.println("Unknown Host :" + args[0]); s = null; } catch(IOException ioe) { // Cannot connect to port on given host System.out.println("Cant connect to server at 12111. Make sure it is running."); s = null; } if(s == null) System.exit(-1);
BufferedReader in = null; PrintWriter out = null; try { // Create the streams to send and receive information in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); // Since this is the client, we will initiate the talking. // Send a string. out.println("Hello"); out.flush(); // receive the reply. System.out.println("Server Says : " + in.readLine()); // Send a string. out.println("This"); out.flush(); // receive a reply. System.out.println("Server Says : " + in.readLine()); // Send a string. out.println("is"); out.flush(); // receive a reply. System.out.println("Server Says : " + in.readLine()); // Send a string. out.println("a"); out.flush(); // receive a reply. System.out.println("Server Says : " + in.readLine());
// Send a string. out.println("Test"); out.flush(); // receive a reply. System.out.println("Server Says : " + in.readLine()); // Send the special string to tell server to quit. out.println("Quit"); out.flush(); } catch(IOException ioe) {
System.out.println("Exception during communication. Server probably closed connection."); } finally { try { // Close the streams out.close(); in.close(); // Close the socket before quitting s.close(); } catch(Exception e) { e.printStackTrace(); } } } }