jalab record

Upload: sssttt1993

Post on 03-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Jalab Record

    1/50

    www.nskinfo.com- College Student and Faculty website

    Department of nskinfo i-education

    Ex No1: Rational Numbers

    AIM To write a Java Program to develop a class for Rational numbers.

    ALGORITHM:

    Step 1:-Declare a class called Rational and invoke a function called gcd(a,b).

    Step 2:-Find out the reminder when a is divided by b and pass it as a parameter to thefunction.

    Step 3:-Create an object for the class and declare the required string and integervariables.

    Step 4:-Create an object of class DataInputStream .Read the numbers through theReadLine() method into the object.

    Step 5:-Convert the input accepted into Integers through the parseInt method and storethem in variables a and b.

    Step 6:-store the value returned by the function GCD in variable l.

    Step 7:-Divide a by l and b by l and store them in variables x and y.

  • 7/29/2019 Jalab Record

    2/50

    Program:-

    import java.io.*;class rational1{

    public rational1(){}

    public long gcd(long a,long b){

    if(b==0)return a;elsereturn gcd(b,a%b);

    }}public class rational{

    public static void main(String args[])throws IOException{

    rational1 r=new rational1();

    long a,b,x,y;String str;DataInputStream in= new DataInputStream(System.in);System.out.println("Enter the value for A");str=in.readLine();a=Integer.parseInt(str);System.out.println("Enter the value for B");str=in.readLine();b=Integer.parseInt(str);

    long l=r.gcd(a,b);System.out.println();System.out.println("The GCD of the number is:"+l);x=a/l;y=b/l;System.out.println();System.out.println("The resultant value is: "+x+"/"+y);

    }}

  • 7/29/2019 Jalab Record

    3/50

    Output

    Enter the value for A500Enter the value for B1000

    The GCD of the number is:500

    The resultant value is: 1/2Ex No 2: Date Class in Java

    AIM

    To design a Date class in Java .

    ALGORITHM:-

    Step 1:Declare a class called Dateexample and create an object called date.

    Step 2:-Display the Date and Time through these objects with theMethods in Date Class.

    Step 3:-Declare two objects called starttime and endtime for this class .

    Step 4:-Create another object called changed object and display the changed time withthe calculation 24L*60L*60L*1000L.

    Step 5:-In the main function create object for the class Date and display the time and dateaccordingly.

  • 7/29/2019 Jalab Record

    4/50

    SOURCE CODE

    import java.util.Date;import java.text.ParseException;import java.text.SimpleDateFormat;public class DateExample {

    private static void DateExample() {

    Date date = new Date();System.out.println("Current Date and Time is : " + date);System.out.println();

    System.out.println("Date object showing specific date and time");Date particulardate1 = new Date(24L*60L*60L*1000L);Date particulardate2 = new Date(0L);System.out.println();System.out.println("First Particular date : " + particulardate1);System.out.println("Second Particular date: " + particulardate2);System.out.println();

    System.out.println("Demo of getTime() method returning milliseconds");System.out.println();Date strtime = new Date();System.out.println("Start Time: " + strtime);Date endtime = new Date();System.out.println("End Time is: " + endtime);

  • 7/29/2019 Jalab Record

    5/50

    long elapsed_time = endtime.getTime() - strtime.getTime();System.out.println("Elapsed Time is:" + elapsed_time + " milliseconds");System.out.println();

    System.out.println("Changed date object using setTime() method");

    System.out.println();Date chngdate = new Date();System.out.println("Date before change is: " + chngdate);chngdate.setTime(24L*60L*60L*1000L);System.out.println("Now the Changed date is: " + chngdate);System.out.println();

    }

    public static void main(String[] args) {System.out.println();DateExample();

    }

    }

    OUTPUT

    Current Date and Time is : Mon Dec 10 18:39:27 GMT+05:30 2007

    Date object showing specific date and time

    First Particular date : Fri Jan 02 05:30:00 GMT+05:30 1970Second Particular date: Thu Jan 01 05:30:00 GMT+05:30 1970

    Demo of getTime() method returning milliseconds

    Start Time: Mon Dec 10 18:39:28 GMT+05:30 2007End Time is: Mon Dec 10 18:39:28 GMT+05:30 2007Elapsed Time is:0 milliseconds

    Changed date object using setTime() method

    Date before change is: Mon Dec 10 18:39:28 GMT+05:30 2007Now the Changed date is: Fri Jan 02 05:30:00 GMT+05:30 1970

  • 7/29/2019 Jalab Record

    6/50

    Ex4 : Implementation of Stack ADT

    AIM

    To write a Java Program to design an interface for Stack ADT.and implementStack ADT using both Array and Linked List.

    ALGORITHM

    Step 1:Declare an array for storing the stack elements and initialise the capacity of thearray.

    Step 2:-Declare functions makeempty(),isempty() to check whether the stack is empty toinsert an element.

    Step 3:After inserting an element,increment the counter by 1 to increase the number ofelements in stack.

    Step 4:Initiate another array to extend the size of the array when the number of elementsexceed beyond the limit.

    Step 5:-Invoke methods and constructors to implement the stack using linked list.

  • 7/29/2019 Jalab Record

    7/50

    Step 6:-Test if the stack is logically empty.then return true or else false.

    Step 7:To delete an element from stack,check if stack is empty,if so throw an exceptionor else move to the next element in the stack.

    Step 8:To return the most recently inserted element use the method topOfStack() andthen move the pointer to the next element.

    Step 9:Declare a stack Interface to push and pop elements from stack.

    Step 10:create two objects one for array and other for linked list implementation of stack.

    Step 11:Insert characters and numbers into the stack using the methods and display theinserted elements with exception blocks.

    SOURCE CODE

    /*** Array-based implementation of the stack.*/public class ArrayStack implements Stack {

    private Object [ ] theArray;private int topOfStack;private static final int DEFAULT_CAPACITY = 10;

    /*** Construct the stack.*/public ArrayStack( ) {

    theArray = new Object[ DEFAULT_CAPACITY ];topOfStack = -1;

    }

    /*** Test if the stack is logically empty.* @return true if empty, false otherwise.*/public boolean isEmpty( ) {

    return topOfStack == -1;

  • 7/29/2019 Jalab Record

    8/50

    }

    /*** Make the stack logically empty.*/

    public void makeEmpty( ) {topOfStack = -1;}

    /*** Get the most recently inserted item in the stack.* Does not alter the stack.* @return the most recently inserted item in the stack.* @throws UnderflowException if the stack is empty.*/public Object top( ) {

    if( isEmpty( ) )throw new UnderflowException( "ArrayStack top" );return theArray[ topOfStack ];

    }

    /*** Remove the most recently inserted item from the stack.* @throws UnderflowException if the stack is empty.*/public void pop( ) {

    if( isEmpty( ) )

    throw new UnderflowException( "ArrayStack pop" );topOfStack--;}

    /*** Return and remove the most recently inserted item* from the stack.* @return the most recently inserted item in the stack.* @throws Underflow if the stack is empty.*/public Object topAndPop( ) {

    if( isEmpty( ) )throw new UnderflowException( "ArrayStack topAndPop" );return theArray[ topOfStack-- ];

    }

    /*** Insert a new item into the stack.* @param x the item to insert.

  • 7/29/2019 Jalab Record

    9/50

    */public void push( Object x ) {

    if( topOfStack + 1 == theArray.length )doubleArray( );

    theArray[ ++topOfStack ] = x;

    }/*** Internal method to extend theArray.*/private void doubleArray( ) {

    Object [ ] newArray;

    newArray = new Object[ theArray.length * 2 ];for( int i = 0; i < theArray.length; i++ )

    newArray[ i ] = theArray[ i ];

    theArray = newArray;}

    }

    //ListStack class//// CONSTRUCTION: with no initializer//// ******************PUBLIC OPERATIONS*********************// void push( x ) --> Insert x// void pop( ) --> Remove most recently inserted item// Object top( ) --> Return most recently inserted item// Object topAndPop( ) --> Return and remove most recent item// boolean isEmpty( ) --> Return true if empty; else false

  • 7/29/2019 Jalab Record

    10/50

    // void makeEmpty( ) --> Remove all items// ******************ERRORS********************************// top, pop, or topAndPop on empty stack

    /**

    * List-based implementation of the stack.*/public class LinkedListStack implements Stack {

    /*** Construct the stack.*/

    public LinkedListStack( ) {topOfStack = null;

    }

    /**

    * Test if the stack is logically empty.* @return true if empty, false otherwise.*/

    public boolean isEmpty( ) {return topOfStack == null;

    }

    /*** Make the stack logically empty.*/

    public void makeEmpty( ) {

    topOfStack = null;}

    /*** Insert a new item into the stack.* @param x the item to insert.*/

    public void push( Object x ) {topOfStack = new ListNode( x, topOfStack );

    }

    /*** Remove the most recently inserted item from the stack.* @throws UnderflowException if the stack is empty.*/

    public void pop( ) {if( isEmpty( ) )

    throw new UnderflowException( "ListStack pop" );topOfStack = topOfStack.next;

  • 7/29/2019 Jalab Record

    11/50

    }

    /*** Get the most recently inserted item in the stack.* Does not alter the stack.

    * @return the most recently inserted item in the stack.* @throws UnderflowException if the stack is empty.*/

    public Object top( ) {if( isEmpty( ) )

    throw new UnderflowException( "ListStack top" );return topOfStack.element;

    }

    /*** Return and remove the most recently inserted item

    * from the stack.* @return the most recently inserted item in the stack.* @throws UnderflowException if the stack is empty.*/

    public Object topAndPop( ) {if( isEmpty( ) )

    throw new UnderflowException( "ListStack topAndPop" );

    Object topItem = topOfStack.element;topOfStack = topOfStack.next;return topItem;

    }

    private ListNode topOfStack;

    }

    public class ListNode {public Object element;public ListNode next;

    // Constructorspublic ListNode( Object theElement ) {

    this( theElement, null );}

  • 7/29/2019 Jalab Record

    12/50

    public ListNode( Object theElement, ListNode n ) {element = theElement;next = n;

    }}

    public interface Stack {/*** Insert a new item into the stack.* @param x the item to insert.*/void push( Object x );

    /*** Remove the most recently inserted item from the stack.

    * @exception UnderflowException if the stack is empty.*/void pop( );

    /*** Get the most recently inserted item in the stack.* Does not alter the stack.* @return the most recently inserted item in the stack.* @exception UnderflowException if the stack is empty.*/Object top( );

    /*** Return and remove the most recently inserted item* from the stack.* @return the most recently inserted item in the stack.* @exception UnderflowException if the stack is empty.*/Object topAndPop( );

    /*** Test if the stack is logically empty.* @return true if empty, false otherwise.*/

    boolean isEmpty( );

    /*** Make the stack logically empty.*/

  • 7/29/2019 Jalab Record

    13/50

    void makeEmpty( );

    }

    public class StackTester {

    public static void main(String[] args) {

    System.out.println("******************************************");System.out.println("Stack using Array & Linked List example");

    System.out.println("******************************************");

    ArrayStack arrayStack = new ArrayStack();arrayStack.push(new String("a"));arrayStack.push(new String("b"));arrayStack.push(new String("c"));System.out.println("Stack[using array] elements -> a, b, c");System.out.println("Stack LIFO and POP -> "+arrayStack.topAndPop());System.out.println("Stack LIFO -> "+arrayStack.top());arrayStack.pop();try{

    arrayStack.pop();arrayStack.topAndPop();}catch(RuntimeException rte){

    System.err.println("Exception occured while POP operation ishappened on Stack[by using array]");

    }System.out.println("\n\n******************************");System.out.println("Stack using Linked List example");System.out.println("******************************");

    LinkedListStack linkedListStack = new LinkedListStack();linkedListStack.push(new Integer(10));linkedListStack.push(new Integer(20));linkedListStack.push(new Integer(30));linkedListStack.push(new Integer(40));System.out.println("Stack[using linked list] elements -> 10, 20, 30, 40");System.out.println("Stack TOP ->"+linkedListStack.top());linkedListStack.pop();System.out.println("Stack TOP after POP ->"+linkedListStack.top());

  • 7/29/2019 Jalab Record

    14/50

    linkedListStack.pop();linkedListStack.pop();linkedListStack.pop();try{

    linkedListStack.pop();

    }catch(RuntimeException rte){System.err.println("Exception occured while POP operation ishappened on Stack[by using linked list]");

    }

    }}

    /**

    * Exception class for access in empty containers* such as stacks, queues, and priority queues.* @author Ramkumar*/

    public class UnderflowException extends RuntimeException {/*** Construct this exception object.* @param message the error message.*/

    public UnderflowException( String message ) {super( message );

    }}

    OUTPUT

    Stack using Array & Linked List example

    ******************************************

    Stack[using array] elements -> a, b, c

    Stack LIFO and POP -> c

    Stack LIFO -> b

    Exception occured while POP operation is happened on Stack[by using array]

    ******************************

  • 7/29/2019 Jalab Record

    15/50

    Stack using Linked List example

    ******************************

    Stack[using linked list] elements -> 10, 20, 30, 40

    Stack TOP ->40

    Stack TOP after POP ->30

    Exception occured while POP operation is happened on Stack[by using linked list]

    Ex no:5 Polymorphism

    Aim:- To develop a vehicle class hierarchy in Java to demonstrate the concept ofpolymorphism.

    Algorithm:-

    Step 1:-Declare a super class called vehicle with data elements doors,wheels and seats.

    Step 2:-Derive another class called car and invoke a function tostring() to display thevariables.

    Step 3:-Derive another class called motorcycle with same data and method calledsetseats() .

    Step 4:-Declare another sub class called Truck with 2 constructors and finally assignvalues to variables.

    Step 5:-In the main function, create an object for class motorcycle and display all detailsof sub classes through object.

    Sourcecode:-

  • 7/29/2019 Jalab Record

    16/50

    //This is the class that will be inheritedpublic class Vehicle{

    public int doors;public int seats;

    public int wheels;Vehicle(){

    wheels=4;doors=4;

    seats=4;}

    }//This class inherits Vehicle.javapublic class Car extends Vehicle{

    public String toString(){return "This car has "+seats+" Seats, "+doors+" Doors "+

    "and "+wheels+" wheels.";}

    }//This class inherits Vehicle.javapublic class MotorCycle extends Vehicle{

    MotorCycle(){

    wheels=2;doors=0;seats=1;

    }void setSeats(int num){

    seats=num;}public String toString(){

    return "This motorcycle has "+seats+" Seats, "+doors+" Doors "+"and "+wheels+" wheels.";

    }}//This class inherits Vehicle.javapublic class Truck extends Vehicle{

    boolean isPickup;Truck()

  • 7/29/2019 Jalab Record

    17/50

    {isPickup=true;

    }Truck(boolean aPickup){

    this();isPickup=aPickup;}Truck(int doors, int seats, int inWheels, boolean isPickup){

    this.doors=doors;this.seats=seats;wheels=inWheels;this.isPickup=isPickup;

    }public String toString()

    { return "This "+(isPickup?"pickup":"truck")+" has "+seats+" Seats, "+doors+" Doors "+"and "+wheels+" wheels.";

    }}//This class tests the classes that inherit Vehicle.javapublic class VehiclesTest{

    public static void main(String args[]){

    MotorCycle mine = new MotorCycle();

    System.out.println(mine);Car mine2 = new Car();System.out.println(mine2);mine2.doors=2;System.out.println(mine2);Truck mine3 = new Truck();System.out.println(mine3);Truck mine4 = new Truck(false);mine4.doors=2;System.out.println(mine4);

    }}

    Output

    This motorcycle has 1 Seats, 0 Doors and 2 wheelsThis car has 4 Seats, 4 Doors and 4 wheels

  • 7/29/2019 Jalab Record

    18/50

    This car has 4 Seats, 2 Doors and 4 wheelsThis pickup has 4 Seats, 4 Doors and 4 wheelsThis truck has 4 Seats, 2 Doors and 4 wheels

    Ex No:-6 Object Serialization

    Aim:-To write a Java Program to randomly generate objects and write them into a fileusing concept of Object Serialization.

    Algorithm:-

    Step 1:Declare a class called Currency .Open a file in output mode with a name.

    Step 2:-Write new data into the object using writeobject() method.

    Step 3:-Similarly create an input stream object .Read it both in terms of Dollars andRupees.close the output object.

    Step 4:-derive a class called Dollar which implements serializable interface.Invoke aconstructor and function to display the data.

    Step 5:Similarly declare a class called Rupee with private variables and use print functionto display the variables.

    Step 6:terminate the execution.The output is displayed as dollar to rupee conversion andvice versa.

    Sourcecode:-

    // Currency conversionimport java.io.*;public class Currency{

    public static void main(String args[]){

    Dollar dr=new Dollar('$',40);dr.printDollar();Rupee re=new Rupee("Rs.",50);

  • 7/29/2019 Jalab Record

    19/50

    re.printRupee();try{File f=new File("rd.txt");FileOutputStream fos=new FileOutputStream(f);

    ObjectOutputStream oos=new ObjectOutputStream(fos);oos.writeObject(dr);oos.writeObject(re);oos.flush();oos.close();ObjectInputStream ois=new ObjectInputStream(new FileInputStream("rd.txt"));Dollar d1;d1=(Dollar)ois.readObject();d1.printDollar();Rupee r1;r1=(Rupee)ois.readObject();

    r1.printRupee();ois.close();}catch(Exception e){}

    }}class Dollar implements Serializable{

    private float dol;private char sym;

    public Dollar(char sm,float doll){

    sym=sm;dol=doll;

    }void printDollar(){

    System.out.print(sym);System.out.println(dol);

    }}class Rupee implements Serializable{

    private String sym;private float rs;public Rupee(String sm,float rup)

  • 7/29/2019 Jalab Record

    20/50

    {sym=sm;rs=rup;

    }void printRupee()

    { System.out.print(sym);System.out.println(rs);

    }

    }

    Output:-

    E:\java>java Currency$40.0Rs.50.0$40.0Rs.50.0

    Ex No:7 Event-Driven Programming

    AIM

    To develop a scientific calculator using even-driven programming paradigm ofJava.

    ALGORITHM:

  • 7/29/2019 Jalab Record

    21/50

    Step 1:-Import all the packages required for designing the graphical elements in theapplet window.

    Step 2:-Implement the Listener files for Keyboard, mouse events in the class defined.

    Step 3:-Import the swing package in the program for using swing components for thrgridLayout design for menu,Frame,Dialog ,TextArea,Label and other components foralignment in the applet window.

    Step 4:-Create objects from the main classes for JLabel,Jtextbox,JPanel ,Font and Menu items.

    Step 5:Assign the font items to all the menu items and add them to the panel.

    Step 6:-Create the GridBagLayout and add all the buttons to it using the swing class.

    Step 7:-Add all the JButtons to the panel and also the colour components to the GUI controls.

    Step 8:-Call adddighitstodisplay() to activate the required arithmetic operations when the buttonsare pressed.

    Step 9:Invoke the function displayresult() to store the result of the values computed.

    Step 10:-Handle the divide by zero exception outside the class definition. And create an objectfor the class created.

    Step 11:-Add all the methods,properties and layout to the panel window and display the result inthe textarea created.

    Step 12:-Invoke the actionPerformed() method through the ActionEvent class and write code foreach operator or number being pressed.

    SOURCE CODE:=-

    import java.awt.BorderLayout;import java.awt.Color;import java.awt.Container;import java.awt.FlowLayout;import java.awt.Font;import java.awt.GridLayout;import java.awt.Window;import java.awt.event.ActionEvent;

  • 7/29/2019 Jalab Record

    22/50

    import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;

    import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.KeyStroke;

    public class Calculator extends JFrame implements ActionListener {

    // Variables

    final int MAX_INPUT_LENGTH = 20;final int INPUT_MODE = 0;final int RESULT_MODE = 1;final int ERROR_MODE = 2;int displayMode;

    boolean clearOnNextDigit, percent;double lastNumber;String lastOperator;

    private JMenu jmenuFile, jmenuHelp;private JMenuItem jmenuitemExit, jmenuitemAbout;

    private JLabel jlbOutput;private JButton jbnButtons[];

    private JPanel jplMaster, jplBackSpace, jplControl;

    /** Font(String name, int style, int size)

    Creates a new Font from the specified name, style and point size.*/

    Font f12 = new Font("Times New Roman", 0, 12);Font f121 = new Font("Times New Roman", 1, 12);

  • 7/29/2019 Jalab Record

    23/50

    // Constructorpublic Calculator(){

    /* Set Up the JMenuBar.* Have Provided All JMenu's with Mnemonics

    * Have Provided some JMenuItem components with KeyboardAccelerators*/

    jmenuFile = new JMenu("File");jmenuFile.setFont(f121);jmenuFile.setMnemonic(KeyEvent.VK_F);

    jmenuitemExit = new JMenuItem("Exit");jmenuitemExit.setFont(f12);

    jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_X,

    ActionEvent.CTRL_MASK));jmenuFile.add(jmenuitemExit);

    jmenuHelp = new JMenu("Help");jmenuHelp.setFont(f121);jmenuHelp.setMnemonic(KeyEvent.VK_H);

    jmenuitemAbout = new JMenuItem("About Calculator");jmenuitemAbout.setFont(f12);

    jmenuHelp.add(jmenuitemAbout);

    JMenuBar mb = new JMenuBar();mb.add(jmenuFile);mb.add(jmenuHelp);setJMenuBar(mb);

    //Set frame layout manager

    setBackground(Color.gray);

    jplMaster = new JPanel();

    jlbOutput = new JLabel("0");jlbOutput.setHorizontalTextPosition(JLabel.RIGHT);jlbOutput.setBackground(Color.WHITE);jlbOutput.setOpaque(true);

    // Add components to frame

  • 7/29/2019 Jalab Record

    24/50

    getContentPane().add(jlbOutput, BorderLayout.NORTH);

    jbnButtons = new JButton[23];// GridLayout(int rows, int cols, int hgap, int vgap)

    JPanel jplButtons = new JPanel(); // container for Jbuttons

    // Create numeric Jbuttonsfor (int i=0; i

  • 7/29/2019 Jalab Record

    25/50

    jbnButtons[i].setForeground(Color.blue);

    elsejbnButtons[i].setForeground(Color.red);

    }

    // Set panel layout manager for a 4 by 5 gridjplButtons.setLayout(new GridLayout(4, 5, 2, 2));

    //Add buttons to keypad panel starting at top left// First rowfor(int i=7; i

  • 7/29/2019 Jalab Record

    26/50

    jplMaster.setLayout(new BorderLayout());jplMaster.add(jplBackSpace, BorderLayout.WEST);jplMaster.add(jplControl, BorderLayout.EAST);jplMaster.add(jplButtons, BorderLayout.SOUTH);

    // Add components to framegetContentPane().add(jplMaster, BorderLayout.SOUTH);requestFocus();

    //activate ActionListenerfor (int i=0; i

  • 7/29/2019 Jalab Record

    27/50

    {if(e.getSource() == jbnButtons[i]){

    switch(i){

    case 0: addDigitToDisplay(i);break;

    case 1:addDigitToDisplay(i);break;

    case 2:addDigitToDisplay(i);break;

    case 3:addDigitToDisplay(i);break;

    case 4:addDigitToDisplay(i);break;

    case 5:addDigitToDisplay(i);

    break;

    case 6:addDigitToDisplay(i);break;

    case 7:addDigitToDisplay(i);break;

    case 8:addDigitToDisplay(i);break;

    case 9:addDigitToDisplay(i);break;

    case 10: // +/-

  • 7/29/2019 Jalab Record

    28/50

    processSignChange();break;

    case 11: // decimal pointaddDecimalPoint();

    break;

    case 12: // =processEquals();break;

    case 13: // divideprocessOperator("/");break;

    case 14: // *

    processOperator("*");break;

    case 15: // -processOperator("-");break;

    case 16: // +processOperator("+");break;

    case 17: // sqrtif (displayMode != ERROR_MODE){

    try{

    if(getDisplayString().indexOf("-") == 0)

    displayError("Invalid inputfor function!");

    result = Math.sqrt(getNumberInDisplay());displayResult(result);

    }

    catch(Exception ex){

    displayError("Invalid input for function!);displayMode = ERROR_MODE;

    }

  • 7/29/2019 Jalab Record

    29/50

    }break;

    case 18: // 1/xif (displayMode != ERROR_MODE){

    try{if (getNumberInDisplay() ==

    0)displayError("Cannot

    divide by zero!");

    result = 1 /getNumberInDisplay();

    displayResult(result);}

    catch(Exception ex) {displayError("Cannot divide

    by zero!");displayMode =

    ERROR_MODE;}

    }break;

    case 19: // %

    if (displayMode != ERROR_MODE){try {result =

    getNumberInDisplay() / 100;displayResult(result);

    }

    catch(Exception ex) {displayError("Invalid input

    for function!");displayMode =

    ERROR_MODE;}

    }break;

    case 20: // backspaceif (displayMode != ERROR_MODE){

  • 7/29/2019 Jalab Record

    30/50

    setDisplayString(getDisplayString().substring(0,

    getDisplayString().length() - 1));

    if (getDisplayString().length() < 1)setDisplayString("0");}break;

    case 21: // CEclearExisting();break;

    case 22: // CclearAll();

    break;}}

    }}

    void setDisplayString(String s){jlbOutput.setText(s);

    }

    String getDisplayString (){

    return jlbOutput.getText();}

    void addDigitToDisplay(int digit){if (clearOnNextDigit)

    setDisplayString("");

    String inputString = getDisplayString();

    if (inputString.indexOf("0") == 0){inputString = inputString.substring(1);

    }

    if ((!inputString.equals("0") || digit > 0)&& inputString.length()