Question

In: Computer Science

Part 1: Write a program that has 2 classes. The first class is a test class...

Part 1:

Write a program that has 2 classes. The first class is a test class with 2 methods; a main method, and a static method called drinkMilk(). The drinkMilk method returns void, and will throw an exception of type OutOfMilkException. The purpose of this exercise is to demonstrate that a method can get information back to the caller through an exceptions object that is thrown inside the called method and caught in the calling method.   (OutOfMilkException is the second class that you will create.)

The drinkMilk method will: save what time you start drinking your milk, here’s how:

            In the System class there is a method:

public static long currentTimeMillis()

Returns the current time in milliseconds.

Then, in an infinite loop, while (true) generate random integers between 0 – 1000 and perform an int division using the random integer as the denominator. Use anything except 0 as the numerator. You must use the Random class to generate random integers, not the Math class. Eventually you will execute a divide by zero.

Each time you generate a random number print out “Gulp.” Use print instead of println. When a division by zero exception is thrown, the drinkMilk method will catch the ArithmeticException exception. Within the catch block throw an exception of type OutOfMilkException.

(You are catching one kind of exception, creating a more descriptive exception that describes the situation, and throwing that exception.)

The outOfMilkException object will contain a value that indicates how long it took to drink the milk – in milliseconds, i.e., how long it took to generate a 0 value. The main method that catches the OutOfMilkException will printout the number of milliseconds that it took to drink the milk.

This demonstrates that information is "thrown" from the drinkMilk method to the main method. Keep in mind that the purpose of this exercise is to “throw” a piece of information from one method to another without using the usual mechanisms for passing information from one method to another, i.e., parameters and return values.

Note: It is not good practice to put any calculation inside an Exception object. These objects are holders of data only! No arithmetic operators, no method calling. Maybe a String concat + once in a while. The methods in the exceptions should never contribute to the solution; their role is exclusively to know about what went wrong, and to be thrown and caught.

Part 2: Assertions

Background:

The ‘assert’ keyword was added to Java in version 1.2. That caused a problem. “assert” was used for many years in C++, and when Java did not provide that mechanism, many Java programmers added a public method called ‘assert’ into their code.   When Java 1.2 came out, all of the code that used ‘assert’ wouldn’t compile, because they had a method name that matched a keyword.

assert somethingTrue;    // does nothing

assert somethingThatIsFalse;    // this will throw an AssertionError

        It became necessary to add some qualifiers to the compile and run commands in Java, so that assertions might be used at compile time and/or at run time. Since we are doing all of our work within Eclipse, you will need to figure out how to turn these on within the Eclipse environment.   Eclipse is generating the commands to compile and run the java programs – that’s good, we don’t have to type the commands, but it makes it harder when we need to change what command is generated.

The compile and run switches for Assertions are quite elaborate. Assertions are only used during development. Everyone will want to turn off this feature at run-time when the product is released.

When you have figured out how to turn Assertions on / off within Eclipse, post your solution on the discussion board. If the answer is already there, but you can add something, do it. You don’t need to re-post something that is already there.

Coding exercise:

Demonstrate using the assert keyword. Create a private method that takes an int parameter.

If the value passed in is negative, the method will assert something that is false, causing the method to throw an AssertionError.

Pass the value that was passed into the method to the constructor of the AssertionError class.

All of this is done with a single assert statement.

Why did I ask you to make this method private? It works the same with public methods. Put a comment in the code if you can find an answer that question. (It isn’t something you can figure out, you will need to read about the convention and the reason for having that convention.)

Solutions

Expert Solution

part1)

import java.util.Random;

public class TestClass {
   public static void main(String[] args) {
       try {
           drinkmilk();
       } catch (OutOfMilkException e) {
           long seconds = System.currentTimeMillis();
           System.out.println(seconds);

       }
   }

   private static void drinkmilk() throws OutOfMilkException {

       while (true) {
           Random r = new Random();
           int lowValue = 0;
           int highValue = 1000;
           int Result = r.nextInt(highValue - lowValue) + lowValue;
           try {
               int division = r.nextInt(100 - 10) + 10 / Result;
               System.out.println("gulp");
           } catch (ArithmeticException e) {
               throw new OutOfMilkException();
           }
       }

   }
}

output

gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
gulp
the time in milliseconds 1486372764126

part2)

to make the assertions apply in eclipse do as following

select ->Run->Run Configuraitons->select java application->right click on java application and click on new ->select arguments ->type in vm arguments

-ea and click on run (assertions are applied in eclipse runtime environment)

for disabling the assertions do same process but in vm arguments type -da and click run

automatically all assertions are disabled in java runtime environment

program

import java.util.Scanner;


public class AssertionTesting {
   static Scanner scanner=new Scanner(System.in);
   public static void main(String[] args) {
       System.out.println("enter the n value");
       int n=scanner.nextInt();
       testAssert( n);
   }
   private static void testAssert(int n) {
       try{
           if(n<0)
           {
               assert false;
           }else
           {
               main(null);
           }
       }catch(AssertionError e)
       {
           throw new AssertionError("the value caused the assertionerror is "+n);
       }
      
   }
}

output

enter the n value
5
enter the n value
-5
Exception in thread "main" java.lang.AssertionError: the value caused the assertionerror is 5
   at AssertionTesting.testAssert(AssertionTesting.java:22)
   at AssertionTesting.main(AssertionTesting.java:9)


Related Solutions

Write a Java program such that it consists of 2 classes: 1. a class that serves...
Write a Java program such that it consists of 2 classes: 1. a class that serves as the driver (contains main()) 2. a class that contains multiple private methods that compute and display a. area of a triangle (need base and height) b area of a circle (use named constant for PI) (need radius) c. area of rectangle (width and length) d. area of a square (side) e. surface area of a solid cylinder (height and radius of base) N.B....
Write a Java program such that it consists of 2 classes: 1. a class that serves...
Write a Java program such that it consists of 2 classes: 1. a class that serves as the driver (contains main()) 2. a class that contains multiple private methods that compute and display a. area of a triangle (need base and height) b area of a circle (use named constant for PI) (need radius) c. area of rectangle (width and length) d. area of a square (side) e. surface area of a solid cylinder (height and radius of base) N.B....
write Java program has two classes ,( using Inheritance ) first class set ( id ,...
write Java program has two classes ,( using Inheritance ) first class set ( id , name ) and method output second class ( id , name , Mark 1 , Mark 2 , Mark 3 ) method total , average , grade , results ( if the student pass or not ) , and output method
Classes and Objects Write a program that will create two classes; Services and Supplies. Class Services...
Classes and Objects Write a program that will create two classes; Services and Supplies. Class Services should have two private attributes numberOfHours and ratePerHour of type float. Class Supplies should also have two private attributes numberOfItems and pricePerItem of type float. For each class, provide its getter and setter functions, and a constructor that will take the two of its private attributes. Create method calculateSales() for each class that will calculate the cost accrued. For example, the cost accrued for...
java Write our Test Driver program that tests our Classes and Class Relationship How we calculate...
java Write our Test Driver program that tests our Classes and Class Relationship How we calculate Net Pay after calculating taxes and deductions taxes: regNetPay = regPay - (regPay * STATE_TAX) - (regPay * FED_TAX) + (dependents * .03 * regPay ) overtimeNetPay = overtimePay - (overtimePay * STATE_TAX) - (overtimePay * FED_TAX) + (dependents * .02 * overtimePay ) Example printPayStub() output: Employee: Ochoa Employee ID: 1234 Hourly Pay: $25.00 Shift: Days Dependents: 2 Hours Worked: 50 RegGrossPay: $1,000.00...
In Python, create a program with 2 classes that do the following. HashCreate class, this class...
In Python, create a program with 2 classes that do the following. HashCreate class, this class will accept a directory and hash each file in the directory and store the results in a dictionary. The dictionary will contain the hash value and file name. HashVerify, the second class will accept the dictionary as input and save that in an instance attribute. This class must also contain a method for lookups that require a file path as input. The lookup method...
Write the following classes: Class Entry: 1. Implement the class Entry that has a name (String),...
Write the following classes: Class Entry: 1. Implement the class Entry that has a name (String), phoneNumber (String), and address (String). 2. Implement the initialization constructor . 3. Implement the setters and getters for all attributes. 4. Implement the toString() method to display all attributes. 5. Implement the equals (Entry other) to determine if two entries are equal to each other. Two entries are considered equal if they have the same name, phoneNumber, and address. 6. Implement the compareTo (Entry...
1. You are to write a simple program with two classes. One controller class and a class to hold your object definition.
1. You are to write a simple program with two classes. One controller class and a class to hold your object definition. (Similar to what we used in class) 2. Use a package in your project, the package name should be xxxprojectname. xxx is your initials taken from the first three characters of your Cal Poly email address. 3. Read in the following from the JOptionPane input window: a. Customer First Name b. Customer Last Name c. Customer Phone Number...
Writing Classes I Write a Java program containing two classes: Dog and a driver class Kennel....
Writing Classes I Write a Java program containing two classes: Dog and a driver class Kennel. A dog consists of the following information: • An integer age. • A string name. If the given name contains non-alphabetic characters, initialize to Wolfy. • A string bark representing the vocalization the dog makes when they ‘speak’. • A boolean representing hair length; true indicates short hair. • A float weight representing the dog’s weight (in pounds). • An enumeration representing the type...
C++ program to implement Matrix Class with following requirements, Classes :- matrix.cpp and main.cpp (to test...
C++ program to implement Matrix Class with following requirements, Classes :- matrix.cpp and main.cpp (to test it) with following requirements: - Please use Vectors of double. Declare and define an matrix class: - The matrix stores doubles. Implement a default constructor which initializes square 1 x 1 matrix that contains  0.0. Implement a constructor that accepts a positive integer n and creates a square n x n matrix that contains 0.0s. Throw an exception if the integer passed to the constructor...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT