/* File: Arithmetic.java For CMSC 220, Fall 1998, U. Wolz, October 1998 */ import javax.swing.*; /* This class implements a two bit binary adder. For example it can handle an addition such as 10 + 11. MODIFY INSTRUCTIONS: Modify this class so that it implements a four bit adder, for example it should handle addition such as 1010 + 0100. Read through the code, answer the questions below and then answer the following: 1. Why store the values of the numbers as booleans instead of int or as 1 & 0. Discuss the tradeoffs. */ class Arithmetic { // Two numbers are received from a user via SimpleGUI methods. These numbers, a and b, are stored // as boolean values. // Data fields // The input number "a" private boolean a1; // the high order bit (2 to the power of 1) private boolean a0; // the low order bit (2 to the power of 0) // The input number "b" private boolean b1; // the high order bit (2 to the power of 1) private boolean b0; // the low order bit (2 to the power of 2) /* Asks for the numbers a and b in turn. Displays the full string of binary digits for each. QUESTION: what is the purpose of passing the result of getInt to dTob? Why not simply ask the user for boolean values, why use digits instead? QUESTION: what are the values 0,1 for in the argument list for getInt. */ public void getDigits() { // QUESTION: explain what happens when the following statement is executed. a1 = dTob( Integer.parseInt(JOptionPane.showInputDialog(null, "a1 digit(0,1): "))); a0 = dTob( Integer.parseInt(JOptionPane.showInputDialog(null, "a0 digit(0,1): "))); JOptionPane.showMessageDialog(null, "a = " + bTod(a1) + bTod(a0)); b1 = dTob(Integer.parseInt(JOptionPane.showInputDialog(null, "b1 digit(0,1): "))); b0 = dTob(Integer.parseInt(JOptionPane.showInputDialog(null, "b0 digit(0,1): "))); JOptionPane.showMessageDialog(null, "b = " + bTod(a1) + bTod(a0)); } /* Creates a FullAdder instance, calculates the low order sum, then uses the low order carry as input to reset the adder to calculate the high order result. QUESTION: why is the first carry argument set to "false". QUESTION: why must the result of the low order sum be stored, why don't any of the other adder results need to be stored locally? */ public void showResult() { FullAdder f = new FullAdder(b0,a0, false); boolean sumOut1 = f.sum(); f.setBits(b1,a1, f.carry()); // QUESTION: explain what happens when this statement is executed. JOptionPane.showMessageDialog(null, "Result " + bTod(f.carry()) + bTod(f.sum()) + bTod(sumOut1)); } // This takes an integer (assumed to be 1 or 0) and returns true if the integer is // equal to 1. // QUESTION: Explain why this method does not require an if then statement. private static boolean dTob(int i) { return (i == 1); } // This takes a boolean value and returns 0 for false, 1 for true. // QUESTION: Explain why this method requires an if then when dTob didn't. private int bTod(boolean b) { if (b) return 1; else return 0; } }