Question

Yet another technique used in combination with console output, flags, and graphical debugging is Asserts. This technique alloAt the end of this method, find the TODO and build a couple of new asserts for use with primitives. a. In the third function

import java.util.ArrayList;
import java.util.Scanner;

public class AssertDemo {

   /* Work on this in a piecewise fashion by uncommenting and focusing on one section at a time
   * in isolation rather than running everything at once.
   */
   public static void main(String[] args) {
       assert(true);
       assert(false);
      
       warmUpAsserts();
      
       assertWithPrimitives();
      
       assertWithObjects();
      
       homeworkRelatedAsserts();
   }

   /*
   * Just a few warm-up asserts here.
   * Add two new assert() statements after the TODO below
   */
   private static void warmUpAsserts() {  
           assert( 5 > 1 );
          
           int a = 30;
           assert(a != 0);
  
           assert(null == null);   //could this ever be false?
           assert(true == true);   //a bad day indeed if this could be false
           //TODO: craft two more asserts and place them here. If they're false, they'll crash the program.
   }

   /*
   * Using asserts in conjunction with primitive types is familiar to you;
   * just as in a loop or if, you want to form a true/false (boolean) expression
   * by employing the relational operators.
   */
   private static void assertWithPrimitives() {
       //assert below to ensure a Fraction's denominator is never 0
       Scanner keys = new Scanner(System.in);
       System.out.println("Enter an integer numerator:");
       int num = keys.nextInt();
              
       System.out.println("Enter an int denominator, not 0:");
       int denom = keys.nextInt();
              
       assert(denom != 0);
  
       //assert that all ArrayLists start empty
       ArrayList<String> emptyList = new ArrayList<String>();
       assert(emptyList.size() == 0);
       //TODO: build two more asserts that use primitives and relational operators here
   }
  
   /*
   * Asserts work with both primitives and objects. Just as you
   * use "==" with primitives and ".equals()" with objects, so too
   * will you use ".equals()" in asserts that deal with object equality.
   */
   private static void assertWithObjects() {
       AssertDemo ad = new AssertDemo();
       ad.checkAddress(ad);      
       //guess what .equals() does if you don't create one yourself? (hint ==)
       assert( ad.equals(ad) );
       //TODO: make a few objects from any previous lab and test them with assert
       //example: make two Point objects at the origin and assert they are equal
       //assert(p1.equals(p2); //example
   }


   /*
   * This function compares the address at "this" to the address of the object handed
   * into the function.
   */
   public void checkAddress(Object input) {
       System.out.println("Address of this :" + this);
       System.out.println("Address of input:" + input);
       //how many aliases for the one "new" object created in main exist in this scope?
       //1? 2? 3? Which are they?
       assert(this == input); //== does an address check for objects, which is frequently NOT what we want
   }

   /*  
   * Asserts are a useful tool for transforming postconditions and class invariants into code.
   * Lets build a few asserts that work with your current Bill & Money assignment.
   * Change the value of paidDate and cents to trip the asserts and observe the asserted error message.
   */
   private static void homeworkRelatedAsserts() {
       Object paidDate = new Object(); //really, a Date
       assert( paidDate != null);     //perhaps one rule is that paidDate shouldn't be null after calling setPaidDate()
       int cents = 0;
       assert( cents >= 0 && cents <=99); //another class invariant is written as an assert here.
       //TODO: craft 2 more asserts that you could use with any assignment
   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please let me know if you have any doubts or you want me to modify the answer. And if you find this answer useful then don't forget to rate my answer as thumps up. Thank you! :)

import java.util.ArrayList;
import java.util.Scanner;

public class AssertDemo {


    public static void main(String[] args) {
        assert(true);
        //assert(false);

        warmUpAsserts();

        assertWithPrimitives();

        assertWithObjects();

        homeworkRelatedAsserts();
    }

    private static void warmUpAsserts() {
        assert( 5 > 1 );

        int a = 30;
        assert(a != 0);

        assert(null == null);  
        assert(true == true);  
        assert(4 == 8/2);
        assert('k' == 'k');
    }


    private static void assertWithPrimitives() {
        Scanner keys = new Scanner(System.in);
        System.out.println("Enter an integer numerator:");
        int num = keys.nextInt();

        System.out.println("Enter an int denominator, not 0:");
        int denom = keys.nextInt();

        assert(denom != 0);

        ArrayList<String> emptyList = new ArrayList<String>();
        assert(emptyList.size() == 0);
        assert(2 > 1);
        int i = 0;
        int j = 0;
        assert(i == j);
    }


    private static void assertWithObjects() {
        AssertDemo ad = new AssertDemo();
        ad.checkAddress(ad);
        assert( ad.equals(ad) );
    }

  
    public void checkAddress(Object input) {
        System.out.println("Address of this :" + this);
        System.out.println("Address of input:" + input);

        assert(this == input);
    }


    private static void homeworkRelatedAsserts() {
        Object paidDate = new Object();
        assert( paidDate != null);    
        int cents = 0;
        assert( cents >= 0 && cents <=99);
        Box a = new Box(1,2,3,4);
        Box b = new Box(1,2,3,4);
        Box c = new Box(a.getWidth(), a.getHeight(),a.getDepth(),a.getGrade());
        Box d = a;
        assert(a.equals(b));
        assert(d.equals(a));
        assert(d == a);
        assert(a.equals(c));
    }
}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class Box{

    private int width, depth;
    private int height, grade;

    public Box(int width, int height, int depth, int grade)
    {
        this.width = width;
        this.height = height;
        this.depth = depth;
        this.grade = grade;
    }

    public boolean equals(Box b)
    {
        return this.getVolume() == b.getVolume() && this.getGrade() == b.getGrade();
    }

   public Box larger(Box b)
    {
        if(b.getVolume() > this.getVolume())
            return b;
        else
            return this;
    }

    public int getGrade()
    {
        return grade;
    }

    public int getVolume()
    {
        return this.width * this.height * this.depth * this.grade;
    }

    public int getWidth()
    {
        return this.width;
    }

    public int getHeight()
    {
        return this.height;
    }

    public int getDepth()
    {
        return this.depth;
    }
}



AssertDemo src/AssertDemo.java AssertDemo AssertDemo src AssertDemo 11 AssertDemo javax Box.java Project import java.util.Arr

Add a comment
Know the answer?
Add Answer to:
import java.util.ArrayList; import java.util.Scanner; public class AssertDemo {    /* Work on this in a piecewise...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • package cards; import java.util.ArrayList; import java.util.Scanner; public class GamePlay { static int counter = 0; private...

    package cards; import java.util.ArrayList; import java.util.Scanner; public class GamePlay { static int counter = 0; private static int cardNumber[] = {1,2,3,4,5,6,7,8,9,10,11,12,13}; private static char suitName[] = { 'c', 'd', 'h', 's' }; public static void main(String[] args) throws CardException, DeckException, HandException { Scanner kb = new Scanner(System.in); System.out.println("How many Players? "); int numHands = kb.nextInt(); int cards = 0; if (numHands > 0) { cards = 52 / numHands; System.out.println("Each player gets " + cards + " cards\n"); } else...

  • Write code for RSA encryption package rsa; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class RSA...

    Write code for RSA encryption package rsa; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class RSA {    private BigInteger phi; private BigInteger e; private BigInteger d; private BigInteger num; public static void main(String[] args) {    Scanner keyboard = new Scanner(System.in); System.out.println("Enter the message you would like to encode, using any ASCII characters: "); String input = keyboard.nextLine(); int[] ASCIIvalues = new int[input.length()]; for (int i = 0; i < input.length(); i++) { ASCIIvalues[i] = input.charAt(i); } String ASCIInumbers...

  • complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class...

    complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Picks the first unguessed word to show. * Updates the guessed array indicating the selected word is shown. * * @param wordSet The set of words. * @param guessed Whether a word has been guessed. * @return The word to show or null if all have been guessed. */    public static String pickWordToShow(ArrayList<String> wordSet, boolean []guessed) { return null;...

  • Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp {    public static void main(String[] args)...

    Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp {    public static void main(String[] args) { displayWelcomeMessage(); // create the Scanner object Scanner sc = new Scanner(System.in); String choice = "y"; while (choice.equalsIgnoreCase("y")) { // generate the random number and invite user to guess it int number = getRandomNumber(); displayPleaseGuessMessage(); // continue until the user guesses the number int guessNumber = 0; int counter = 1; while (guessNumber != number) { // get a valid int from user guessNumber...

  • PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class...

    PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class definition. * * @author David Brown * @version 2019-01-22 */ public class Movie implements Comparable { // Constants public static final int FIRST_YEAR = 1888; public static final String[] GENRES = { "science fiction", "fantasy", "drama", "romance", "comedy", "zombie", "action", "historical", "horror", "war" }; public static final int MAX_RATING = 10; public static final int MIN_RATING = 0; /** * Converts a string of...

  • departmentstore: package departmentstorepkg; import java.util.ArrayList; public class DepartmentStore {    private static final int DEFAULT_SIZE =...

    departmentstore: package departmentstorepkg; import java.util.ArrayList; public class DepartmentStore {    private static final int DEFAULT_SIZE = 10; private StaffMember [] myEmployees; private int myNumberEmployees; private String myFileName; private StaffMember[] employee; public DepartmentStore (String filename){ myFileName = filename; myEmployees = employee;    } public String toString(){ return this.getClass().toString() + ": " + myFileName; } public void addEmployee(Employee emp){ } /** * prints out all the employees in the array list held in this class */ public void print(){ for(int i =...

  • Make a FLOWCHART for the following JAVA Prime Number Guessing Game. import java.util.Random; import java.util.Scanner; public...

    Make a FLOWCHART for the following JAVA Prime Number Guessing Game. import java.util.Random; import java.util.Scanner; public class Project2 { //Creating an random class object static Random r = new Random(); public static void main(String[] args) {    char compAns,userAns,ans; int cntUser=0,cntComp=0; /* * Creating an Scanner class object which is used to get the inputs * entered by the user */ Scanner sc = new Scanner(System.in);       System.out.println("*************************************"); System.out.println("Prime Number Guessing Game"); System.out.println("Y = Yes , N = No...

  • import java.util.Scanner; import java.util.ArrayList; public class P3A2_BRANDT_4005916 {    public static void main(String[] args)    {...

    import java.util.Scanner; import java.util.ArrayList; public class P3A2_BRANDT_4005916 {    public static void main(String[] args)    {        String name;        String answer;        int correct = 0;        int incorrect = 0;        Scanner phantom = new Scanner(System.in);        System.out.println("Hello, What is your name?");        name = phantom.nextLine();        System.out.println("Welcome " + name + "!\n");        System.out.println("My name is Danielle Brandt. "            +"This is a quiz program that...

  • import java.util.Scanner; public class TriangleMaker {    public static void main(String[] args) {        //...

    import java.util.Scanner; public class TriangleMaker {    public static void main(String[] args) {        // TODO Auto-generated method stub        System.out.println("Welcome to the Triangle Maker! Enter the size of the triangle.");        Scanner keyboard = new Scanner(System.in);    int size = keyboard.nextInt();    for (int i = 1; i <= size; i++)    {    for (int j = 0; j < i; j++)    {    System.out.print("*");    }    System.out.println();    }    for (int...

  • please debug this code: import java.util.Scanner; import edhesive.shapes.*; public class U2_L7_Activity_Three{ public static void main(String[] args){...

    please debug this code: import java.util.Scanner; import edhesive.shapes.*; public class U2_L7_Activity_Three{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); double radius; double length; System.out.println("Enter radius:"); double r = scan.nextDouble(); System.out.println("Enter length:"); double l = scan.nextDouble(); System.out.println("Enter sides:"); int s = scan.nextInt(); Circle c = Circle(radius); p = RegularPolygon(l , s); System.out.println(c); System.out.println(p); } } Instructions Debug the code provided in the starter file so it does the following: • creates two Double objects named radius and length creates...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT