Assignment 14:

Lab Exercise 9

Java – Calculator Using Static Class

Introduction

Write an interactive console program that performs like a simple calculator, just like you did in Lab 11 Menu Driven Calculator.  In this lab, remove all methods for math operation from the main class and place them in a separate static class.

Objectives

This purpose of this lab assignment is to help students build problem-solving skills. It uses static methods inside a class. It also uses control structures to write a simple utility program.

  • Understand and be able to write code for decision making
  • Be able to analyze a reasonably complex problem and solve it using a computer program
  • Understand and be able to write modular code using basic object oriented programming techniques
  • Understand and be able to use a static class library
  • Understand be able to format and display output to user

Details:

Write a simple program that displays a menu as shown below. When user selects an option, it performs a mathematical operation.

Requirements

  • Make program as modular as possible (use methods)
  • Must use a separate class “MyMathLib” to get any credit for this lab
  • The class must have the following static methods.

static double Add(double a, double b)

static double Subtract(double a, double b)

static double Multiply(double a, double b)

static double Divide(double a, double b)

static double Modulus(double a, double b)

  • The main class (the test class that uses the static class) must have the following methods. Menu can be in a separate class if you want to.

public static void main

static void runSelection(int Selection, int number1, int number2)

static void displayMenu()

staticintvalidateSelection(int res)

Test Cases

Expected Output

Calculator Menu

  1. Add
  2. Subtract
  3. Multiply
  4. Divide
  5. Modulus
  6. Quit

———————-

Enter you select [1-6]: 1

Enter the first number: 10

Enter the second number: 2

Sum of 10, 2 is 12

Press any key to continue….

Calculator Menu

  1. Add
  2. Subtract
  3. Multiply
  4. Divide
  5. Modulus
  6. Quit

———————-

Enter you select [1-6]: 2

Enter the first number: 50

Enter the second number: 25

Difference of 50, 25 is 25

Press any key to continue….

Calculator Menu

  1. Add
  2. Subtract
  3. Multiply
  4. Divide
  5. Modulus
  6. Quit

———————-

Enter you select [1-6]: 3

Enter the first number: 10

Enter the second number: 2

Product of 10, 2 is 20

Press any key to continue….

Calculator Menu

  1. Add
  2. Subtract
  3. Multiply
  4. Divide
  5. Modulus
  6. Quit

———————-

Enter you select [1-6]: 4

Enter the first number: 0

Enter the second number: 10

Dividing 0 by 10 is 0

Press any key to continue….

Calculator Menu

  1. Add
  2. Subtract
  3. Multiply
  4. Divide
  5. Modulus
  6. Quit

———————-

Enter you select [1-6]: 4

Enter the first number: 16

Enter the second number: 0

Cannot divide by zero. Please try again with valid values.

Press any key to continue….

Calculator Menu

  1. Add
  2. Subtract
  3. Multiply
  4. Divide
  5. Modulus
  6. Quit

———————-

Enter you select [1-6]: 5

Enter the first number: 17

Enter the second number: 3

Modulus of 17 and 3 is 2

Press any key to continue….

Calculator Menu

  1. Add
  2. Subtract
  3. Multiply
  4. Divide
  5. Modulus
  6. Quit

———————-

Enter you select [1-6]: 6

Good bye…

Press any key to continue . . .

Solution for Lab Exercise 9:

MyMathLib.java

// Library class to perform basic match operations

public class MyMathLib {

// add

static double Add(double a, double b) {

return a + b;

}

// subtract

static double Subtract(double a, double b) {

return a – b;

}

// multiply

static double Multiply(double a, double b) {

return a * b;

}

// divide

static double Divide(double a, double b) {

return a / b;

}

// modulus

static double Modulus(double a, double b) {

return a % b;

}

}

MyMathLibTest.java

importjava.util.Scanner;

public class MyMathLibTest {

public static void main(String[] args) {

// to read from user

Scanner scanner = new Scanner(System.in);

boolean quit = false;

while (!quit) { //while user doesn’t quit

displayMenu(); //show menu

// read choice

System.out.print(“Enter your select [1-6]: “);

int choice = scanner.nextInt();

//if valid

if (validateSelection(choice)) {

if (choice == 6) { //if quit

quit = true;

System.out.println(“Good bye…”);

} else {

//read two numbers

System.out.print(“Enter the first number: “);

int number1 = scanner.nextInt();

System.out.print(“Enter the second number: “);

int number2 = scanner.nextInt();

// perform operations

runSelection(choice, number1, number2);

}

} else { //if no a valid selection

System.out.println(“Error: Invalid choice.”);

}

System.out.println(“Press any key to continue….”);

scanner.nextLine();

scanner.nextLine();

}

scanner.close();

}

// perform operations based on user choice and two numbers

static void runSelection(int Selection, int number1, int number2) {

switch (Selection) {

case 1: //add

int result = (int) MyMathLib.Add(number1, number2);

System.out.println(“Sum of ” + number1 + “, ” + number2 + ” is ” + result);

break;

case 2: // subtract

result = (int) MyMathLib.Subtract(number1, number2);

System.out.println(“Diference of ” + number1 + “, ” + number2 + ” is ” + result);

break;

case 3: // multiply

result = (int) MyMathLib.Multiply(number1, number2);

System.out.println(“Product of ” + number1 + “, ” + number2 + ” is ” + result);

break;

case 4: //divide

if (number2 == 0) //divisor is zero

System.out.println(“Cannot divide by zero. Please try again with valid values.”);

else {

result = (int) MyMathLib.Divide(number1, number2);

System.out.println(“Dividing ” + number1 + ” by ” + number2 + ” is ” + result);

}

break;

case 5: // modulus

if (number2 == 0) //divisor is zero

System.out.println(“Cannot divide by zero. Please try again with valid values.”);

else {

result = (int) MyMathLib.Modulus(number1, number2);

System.out.println(“Modulus of ” + number1 + ” and ” + number2 + ” is ” + result);

}

break;

}

}

// displays a menu to user

static void displayMenu() {

System.out.println(“Calculator Menu”);

System.out.println(“1.      Add”);

System.out.println(“2.      Subtract”);

System.out.println(“3.      Multiply”);

System.out.println(“4.      Divide”);

System.out.println(“5.      Modulus”);

System.out.println(“6.      Quit”);

System.out.println(“———————-“);

}

// validates if the selection is between 1 and 6 only

staticbooleanvalidateSelection(int res) {

if (res < 1 || res > 6)

return false;

else

return true;

}

}

Lab Exercise 10

Java – Rolling dice

Introduction

Write a Java interactive console application that simulates rolling two die 36 million times and calculate percentage of each face value (values will be from 2 to 12). This Ex 7.17 in the Java textbook. 

Objectives

This purpose of this lab assignment is to help students build problem solving skills. It use methods and control structures to write a simple computer game program.

  • Understand and be able to write code for decision making
  • Understand and be able to write code that interacts with a user
  • Understand be able to use if/else if else statement
  • Understand be able to use relational operators for comparing numbers
  • Understand be able format and display output to user

 Details:

Write a Java interactive console application that simulates rolling two die 36 million times and calculate percentage of each face value (values will be from 2 to 12). The following table/diagram shows what the odd of getting each value is. Compare your results it to see if this makes sense.

The vertical and horizontal headers simulate the result of one dice each. For example, you can only get 2 by rolling a 1 on each dice, but you can get a 7 with 6 combinations (1:6, 2:5, 3:4, 4:3, 5:2, 6:1).

1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
3 4 5 6 7 8 9
4 5 6 7 8 9 10
5 6 7 8 9 10 11
6 7 8 9 10 11 12

Expected output:

Sum   Frequency  Percentage

2     1003106        2.79

3     1999281        5.55

4     2998131        8.33

5     4003685       11.12

6     4998964       13.89

7     5995418       16.65

8     4999907       13.89

9     4001769       11.12

10     2998696        8.33

11     2000460        5.56

12     1000583        2.78

You will not get the exact answer, but it should be very close.

Hints:

  • Keep track of how many times each total (2 through 12) occurs. This total is used to calculate the percentageof the time that each total occurs.
  • Define a loop that iterates 36,000 times. During each iteration, roll two dice. Use the sum of the dice as an index to array totals and increment that element of the array (updatethe count for the particular array element).
  • Create an array large enough that you can use the sum of the dice as the index into the array.

int face1; // number on first die

int face2; // number on second die

int[] totals = newint[13]; // frequencies of the sums

Solution for Lab Exercise 10: 

DiceThrows.java

importjava.util.Random;

public class DiceThrows {

public static void main(String[] args) {

finalint TOTAL_RUNS = 36000000;

int face1; // number on first die

int face2; // number on second die

int[] totals = new int[13]; // frequencies of the sums

// initialize array totals to zeros

for (int i = 0; i <totals.length; i++) {

totals[i] = 0;

}

// to generate random numbers for dice throws

Random random = new Random();

// loop 36 million times. Roll the dice in the loop and assign values to

// face1 and face2.

for (int i = 0; i < TOTAL_RUNS; i++) {

face1 = 1 + random.nextInt(6);

face2 = 1 + random.nextInt(6);

totals[face1+face2]++;

}

// In the loop, use the sum of face1 and face2 the index of totals and

// increment that array element.

// Display the content of array totals. Ignore subscripts 0 and 1

System.out.printf(“%-5s %-15s %s\n”, “Sum”, “Frequency”, “Percentage”);

for (int i = 2; i <totals.length; i++) {

doublepercentae = totals[i] * 100.0/ TOTAL_RUNS;

System.out.printf(“%2s    %-15d %.2f\n”, i, totals[i], percentae);

}

}

}

Lab Exercise 11

Java – Simple Array Class

Introduction

Write a Java console application that whose data is made up of an array of integers. Later on, you will write an application whose data will be an array of employees. 

Objectives

This purpose of this lab assignment is to help students build problem solving skills and reinforces topics learned in Chapter7 – Arrays and ArrayList.

  • Understand how to create use single dimensional arrays. 

Details:

Write a Java console application that whose data is made up of an array of integers. Your program will consist of 2 classes, IntegerData Class and DataTester Class.

IntegerData Class

IntegerData Class has the following fields and methods.

publicclassIntegerData

//Two fields or instance variables.

privateint[] arr;

privateintiNumElements;    //# of elements in the array, not the size of the array.

//Constructor. Initializes both instance variables. Does not

// create a new array.

publicIntegerData(int[] arr, intiNumElements)

// Displaysthe ith element

publicvoidDisplayAt(int i)

// Display all elements in the array that have a value

publicvoidDisplayAll()

// Key – value to search in the array

// return value – index where key was found

publicint Find(int key)

// delete ‘key’ from the array.

// which means that you must move up rest of the elements.

publicvoid Delete(int key)

// sort the array using bubble sort

publicvoidbubbleSort()

// insert an element in the array.

publicvoidinsert(int n)

end of classIntegerData

publicintFind(int key)

The key variable holds the value we’re looking for. To search for an item, we step through the array, comparing key with each element. If the loop variable reaches the last occupied cell of the array with no match being found, the value isn’t in the array. If it finds a match, it returns that index of the array, otherwise it returns -1. 

publicvoid insert(int n)

This method insert adds a new int into the array and increment iNumElements(count) by one.

public void Delete(intkey) { // delete person from array

This method first searches the array to see if the key is the array. If it is, then it removes that entry from the array. Since an entry is removed from the array, all array members must be moved up. Note: We don’t remove an item; we simply overwrite it with the next item of the array and move up rest of the items too.

public void DisplayAt(inti)// displays the value at index i.

Goes through the array and displays the entry at index i.

public void DisplayAll()  // displays the values of the array.

// sorts the array using the bubblesort sorting algorithm.

publicvoidbubbleSort() {

int out, in;

int temp;

for (out = iNumElements – 1; out > 0; out–) // outer loop (backward)

{

for (in = 0; in < out; in++) // inner loop (forward)

{

// combined the old “swap” into the “if” loop

if (arr[in] >arr[in + 1]) {

temp = arr[in];

arr[in] = arr[in + 1];

arr[in + 1] = temp;

} // end if

} // inner for loop

} // outer for loop

} // end bubbleSort()

DataTester Class

Your main program will create an array of integer, populate it with some values and then create an object of IntegerData class and pass it the array and number of elements in that array.

IntegerData’s constructor will use these valuesto initialize IntegerData class.

Since arrays are static, we will allocate a large array (in the DataTester class) and then use a variable to keep track of items in that array.

Requirements

  • Make program as modular as possible. You must have an IntegerData classand a main program class.
  • Your program should be able to Insert, Search, Display, DisplayAll, Find, Sort and Delete a value.
  • The content of the main class is as follows:

int[] arr = newint[100];

arr[0] = 77;               // insert 10 items

arr[1] = 99;

arr[2] = 44;

arr[3] = 55;

arr[4] = 22;

arr[5] = 88;

arr[6] = 11;

arr[7] = 3;

arr[8] = 66;

arr[9] = 33;

intnElems = 10;                   // now 10 items in array

MyArrayClassarrayObj= newMyArrayClass(arr, nElems);

System.out.format(“\nDisplaying all members of the array\n”);

arrayObj.DisplayAll();

System.out.format(“\nDisplaying element at index 6 of the array\n”);

arrayObj.DisplayAt(6);

System.out.format(“\nFind 55 in the array\n”);

if (arrayObj.Find(55) != -1) {

System.out.format(“Number 55 was found at index %d of the array\n”, arrayObj.Find(55));

}

else {

System.out.format(“Number 55 was NOT found.\n”);

}

System.out.format(“\nDelete 55 from the array\n”);

arrayObj.Delete(55);

 

System.out.format(“\nFind 55 in the array\n”);

if (arrayObj.Find(55) != -1) {

System.out.format(“Number 55 was found at index %d of the array\n”, arrayObj.Find(55));

}

else {

System.out.format(“Number 55 was NOT found.\n”);

}

System.out.format(“\nDisplaying all members of the array\n”);

arrayObj.DisplayAll();

System.out.format(“\nSorting the array\n”);

arrayObj.bubbleSort();

System.out.format(“\nDisplaying all members of the array\n”);

arrayObj.DisplayAll();

System.out.format(“\nInset 49 into the array and then display array\n”);

arrayObj.insert(49);

arrayObj.DisplayAll(); 

Test Cases

  1. Start by creating ArrayMain.java file which has the main method. Copy the above content into the main method.
  2. Add a package (optional) and then add a class fileMyArrayClass in the package.
  3. In the class file, there are two fields (instance variables) as follows:

privateint[] arr;

privateintiNumElements;

  1. Add a constructor that initializes the two instance variables.
  2. Add all the methods mentioned above. For now just create the stubs, then later implement each method one at a time.

Test Cases

Displaying all members of the array

77 99 44 55 22 88 11  3 66 33

Displaying element at index 6 of the array

Value at index 6 is: 11

Find 55 in the array

Number 55 was found at index 3 of the array

Delete 55 from the array

Find 55 in the array

Number 55 was NOT found.

Displaying all members of the array

77 99 44 22 88 11  3 66 33

Sorting the array

Displaying all members of the array

3 11 22 33 44 66 77 88 99

Inset 49 into the array and then display array

3 11 22 33 44 66 77 88 99 49 

Solution for Lab Exercise 11:

ArrayMain.java

public class ArrayMain {

public static void main(String[] args) {

int[] arr = new int[100];

arr[0] = 77; // insert 10 items

arr[1] = 99;

arr[2] = 44;

arr[3] = 55;

arr[4] = 22;

arr[5] = 88;

arr[6] = 11;

arr[7] = 3;

arr[8] = 66;

arr[9] = 33;

intnElems = 10; // now 10 items in array

// display all

MyArrayClassarrayObj = new MyArrayClass(arr, nElems);

System.out.format(“\nDisplaying all members of the array\n”);

arrayObj.DisplayAll();

// display element at 6

System.out.format(“\nDisplaying element at index 6 of the array\n”);

arrayObj.DisplayAt(6);

// find 55

System.out.format(“\nFind 55 in the array\n”);

if (arrayObj.Find(55) != -1) {

System.out.format(“Number 55 was found at index %d of the array\n”, arrayObj.Find(55));

} else {

System.out.format(“Number 55 was NOT found.\n”);

}

//delete 55

System.out.format(“\nDelete 55 from the array\n”);

arrayObj.Delete(55);

// find 55

System.out.format(“\nFind 55 in the array\n”);

if (arrayObj.Find(55) != -1) {

System.out.format(“Number 55 was found at index %d of the array\n”, arrayObj.Find(55));

} else {

System.out.format(“Number 55 was NOT found.\n”);

}

// diskay all

System.out.format(“\nDisplaying all members of the array\n”);

arrayObj.DisplayAll();

// bubble sort

System.out.format(“\nSorting the array\n”);

arrayObj.bubbleSort();

// display all

System.out.format(“\nDisplaying all members of the array\n”);

arrayObj.DisplayAll();

// insert

System.out.format(“\nInset 49 into the array and then display array\n”);

arrayObj.insert(49);

// display all

arrayObj.DisplayAll();

}

}

 

MyArrayClass.java

public class MyArrayClass {

// Two fields or instance variables.

privateint[] arr;

privateintiNumElements; // # of elements in the array

// Constructor. Initializes both instance variables. Does not

// create a new array.

publicMyArrayClass(int[] arr, intiNumElements) {

this.arr = arr;

this.iNumElements = iNumElements;

}

// Displays the ith element

public void DisplayAt(int i) {

System.out.println(arr[i]);

}

// Display all elements in the array that have a value

public void DisplayAll() {

for (int i = 0; i <iNumElements; i++) {

System.out.print(arr[i] + ” “); // display elemnt sin same line

// separated by space

}

// move to new line

System.out.println();

}

// Key – value to search in the array

// return value – index where key was found

publicint Find(int key) {

// for each element

for (int i = 0; i <iNumElements; i++) {

if (arr[i] == key) // if found

return i;

}

// not found

return -1;

}

// delete ‘key’ from the array.

// which means that you must move up rest of the elements.

public void Delete(int key) {

int index = Find(key); // find index

 

if (index == -1) // not found

return;

// move next elements one step back

for (int i = index + 1; i <iNumElements; i++) {

arr[i – 1] = arr[i];

}

// reduce number of elements

iNumElements–;

}

// sort the array using bubble sort

public void bubbleSort() {

int out, in;

int temp;

for (out = iNumElements – 1; out > 0; out–) {// outer loop (backward)

for (in = 0; in < out; in++) {// inner loop (forward)

// combined the old “swap” into the “if” loop

if (arr[in] >arr[in + 1]) {

temp = arr[in];

arr[in] = arr[in + 1];

arr[in + 1] = temp;

}

}

}

}

// insert an element in the array.

public void insert(int n) {

arr[iNumElements++] = n; // add the number and increment number of

// elements

}

}