Question

In: Computer Science

Question #1 The commented codes in the Driver class are either causing a syntax error or...

Question #1

The commented codes in the Driver class are either causing a syntax error or run time error. Make sure to identify the error yourself without running it.

predict the output once you fix all the errors.

  1. un-comment one line at a time
  2. identify the error
  3. fix just that line, You are not allowed to change any declarations of the objects.
  4. if it is a runtime error explain the error
  5. compile the code.
  6. move to the next error

Make sure you are able to answer similar question if it appears in the exam.

public class Cup extends Box {
    public void method1() {
        System.out.println("Cup 1");
    }

    public void method2() {
        System.out.println("Cup 2");
        super.method2();
    }
}

 class Pill {
    public void method2() {
        System.out.println("Pill 2");
    }
}

class Jar extends Box {
    public void method1() {
        System.out.println("Jar 1");
    }

    public void method2() {
        System.out.println("Jar 2");
    }
}

class Box extends Pill {
    public void method2() {
        System.out.println("Box 2");
    }

    public void method3() {
        method2();
        System.out.println("Box 3");
    }
}
class Driver
{
  public static void main(String[] args)
  {
      Box var1 = new Box();
      Pill var2 = new Jar();
      Box var3 = new Cup();
      Box var4 = new Jar();
      Object var5 = new Box();
      Pill var6 = new Pill();
      var1.method2();
      var2.method2();
      var3.method2();
      var4.method2();
     // var5.method2();  //error
      var6.method2();
      var1.method3();
     // var2.method3();//error
      var3.method3();
      var4.method3();
      //((Cup)var1).method1(); //runtime error
      ((Jar)var2).method1();
      ((Cup)var3).method1();
     // ((Cup)var4).method1(); //runtime error
      ((Jar)var4).method2();
      ((Box)var5).method2();
     // ((Pill)var5).method3();//error
      ((Jar)var2).method3();
      ((Cup)var3).method3();
     // ((Cup)var5).method3();//runtime error
      

  }

}

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

Question 2

Comparable Programming. Suppose you have a pre-existing class BankAccount that represents users' accounts and money deposited at a given bank. The class has the following data and behavior:

Field/Constructor/Method

Description

private String name

name of the person using the account

private int id

ID number of this account

private double balance

amount of money currently in the account

public BankAccount(String name, int id)

makes account with given name/ID and $0.00

public void deposit(double amount)

adds given amount to account's balance

public int getID()

returns the account's ID number

public String getName()

returns the account's name

public double getBalance()

returns the account's balance

public String toString()

returns String such as "Ed Smith: $12.56"

public void withdraw(double amount)

subtracts given amount from account's balance

Make BankAccount objects comparable to each other using the Comparable interface.

use the following rules to implement the compareTo method

  • The bank wants to sort by who has the most money, so accounts are compared by balance.
  • One with a lower balance is considered to be "less than" one with a higher balance.
  • If two accounts have the same balance, they are compared by ID.
  • The one with the lower ID is considered to be "less than" the one with the higher ID.
  • If two accounts have the same balance and ID, they are considered to be "equal." Your method should not modify any account's state. You may assume the parameter passed is not null.

public class BankAccount implements Comparable {

    public int compareTo(Object o) {
         BankAccount other = (BankAccount)o;
        if (balance > other.getBalance()) {

            return 1;

        } else if (balance < other.getBalance()) {

            return -1;

        } else if (id > other.getID()) {

            return 1;

        } else if (id < other.getID()) {

            return -1;

        } else {

            return 0;

        }

    }

}

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

Question 3

Add a compreTo method to the Passenger class that you created for the previous assignment. Passengers should be compared based on their last names. If two passengers have the same last name then the seat numbers must be compared.

Solution

 public int compareTo(Object o)
  {
     Passenger p = (Passenger)o;
     //checking to see if the last names are the same, if it is then compare based on the seat number
     if (this.getLast().equalsIgnoreCase(p.getLast()))   
         return this.seatNumber - p.seatNumber; 
     else
      return  this.getLast().compareTo(p.getLast());     //if the last names are not the same then compare the last names  
        
  }

PreviousNext

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

Question 4

You should be able to answer the following questions

Part 1.create an interface called Incrementable that has two methods called increment and decrement. both of these methods have a parameter of type integer and they don't return anything.

part 2:

The following code does not compile. what is the issue? how can you fix the problem

interface Pay
{
   public double getRaise();
   public String getPromotion(double num);
}
class Secretary implements Pay
{
   public Secretary()
   {
   }
   public void getRaise()
   {
      System.out.println("You got a Raise");
   }
   public double getPromotion(int num)
   {
      System.out.println("You got " +num + " promotion");
   }
} 

dsfdfdf

PreviousNext

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

question 5

Suppose that the following two classes have been declared:

 public class Car {
    public void m1() {
        System.out.println("car 1");
    }
​
    public void m2() {
        System.out.println("car 2");
    }
​
    public String toString() {
        return "vroom";
    }
}
class Truck extends Car {
    public void m1() {
        System.out.println("truck 1");
    }
     
    public void m2() {
        super.m1();
    }
     
    public String toString() {
        return super.toString() + super.toString();
    }
}

Write a class MonsterTruck whose methods have the behavior below. Don't just print/return the output; use inheritance to reuse behavior from the superclass.

Method Output/Return
m1 : monster 1
m2 : truck 1

car 1
toString: "monster vroomvroom"

Solution

 class MonsterTruck extends Truck
 {
   public void m1()
   {
      System.out.println("Monster 1");
   }
   public void m2()
   {
      super.m1();
      super.m2();
   }
   public String toString()
   {
      return "Monster "+ super.toString();
   }
    } 
class Driver
{
   public static void main(String[]args)
   {
      MonsterTruck m = new MonsterTruck();
      m.m1();
      m.m2();
      System.out.println(m);
      
   }
}

your turn:

the following classes have been created.

class Eye extends Mouth {
    public void method1() {
       System.out.println("Eye 1");
        
    }
}

 class Mouth {
    public void method1() {
        System.out.println("Mouth 1");
    }

    public void method2() {
        System.out.println("Mouth 2");
        
    }
}

class Nose extends Eye {
    public void method1() {
        System.out.println("Nose 1");
    }

    public void method3() {
        System.out.println("Nose 3");
    }
}




create a class called Ear that extends Nose. this class must implement the method1, method2, method3 . After creating the Ear class the following drive should generate the given output

 class Driver
{
   public static void main(String[] args)
   {
      Ear e = new Ear();
      System.out.println("calling method 1");
      e.method1();
      System.out.println("calling the method 2");
      e.method2();
      System.out.println("calling the method 3");
      e.method3();
   }
}

Output: 
calling method 1
Nose 1
Ear1
calling the method 2
Ear 2
Mouth 2
calling the method 3
Ear 3
Nose 1

public class Ear extends  Nose
{
    //your code
}

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

Question 6

The following classes have been created.

public class Plate
{
    public void method1()
    {
      System.out.println("Plate");
    }
}
class Fork 
{
  public void method2()
  {
     System.out.println("Fork");
  }
}
class Spoon
{
   public void method3()
   {
      System.out.println("Spoon");
   }
}

The following driver has been created but it does not compile. what is the cause of the error and how can you fix it.

class Driver
{
   public static void main(String[] args)
   {
     Object[] stuff = {new Spoon(), new Fork(), new Plate()};
     for(int i = 0; i < stuff.length; i++)
     {
         stuff[i].method1();
         Stuff[i].method2();
         stuff[i].method3();
     }
   }
}

solution: since there is an array of Objects, every element in the array must be type casted to the proper type. then the method from the class can be called on it.

class Driver
{
   public static void main(String[] args)
   {
     Object[] stuff = {new Spoon(), new Fork(), new Plate()};
     for(int i = 0; i < stuff.length; i++)
     {
         if(stuff[i] instanceof Plate)
         {
            Plate p = (Plate)stuff[i];
            p.method1();
         }
         else if(stuff[i] instanceof Fork)
         {
            Fork f = (Fork)stuff[i];
            f.method2();
         }
         else if(stuff[i] instanceof Spoon)
         {
            Spoon s = (Spoon)stuff[i];
            s.method3();
         }

    }
   }
}

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

Question 7

There will one question related to ArrayList class similar to the following question.

The following driver has created a an ArrayList of Point objects. write a method that moves all the points with the value of x greater than its value of y to the end of the list. .  

import java.util.*;
public class ArrayistQuestion
{
  public static void main(String[] args)
  {
     ArrayList<Point> points = new ArrayList<Point>();
     points.add(new Point(12, 5));
     points.add(new Point(2,23));
     points.add(new Point(6,3));
     points.add(new Point(9,2));
     points.add(new Point(12,23));
     System.out.println(points);
     shift(points);
     System.out.println(points);
  }
  //this method shifts all the points with x greater than y to the end of the list
  public static void shift(ArrayList<Point> list)
  {
     int count = list.size();
     for(int i = 0; i < count; i++)
     {
        if(list.get(i).getX() > list.get(i).getY())
        {
           Point p = list.get(i); //make a copy of the Point object
           list.remove(i);//removes it from the list
           list.add(p);  // adds it ot the endof the list
           i--;
           count--; // decrement the count by 1 since one element has been removed
        }
     }
  }
}
class Point
{
   private int x;
   private int y;
   public Point(int x, int y)
   {
     this.x = x;
     this.y = y;
   }
   public int getX()
   {
     return x;
   }
   public int getY()
   {
     return y;
   }
   public String toString()
   {
     return "(x = "+ x + " y = " + y+" )";
   }
   }

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

Solutions

Expert Solution

Ans 1)

i) First Error : Object var5 = new Box()

Instead of writiing the above Syntax it must be written as :

Box var5 = new Box();  

ii ) Second Error: Pill var2 = new Jar();

First we need to create an object of child class in inheritence. Therefore we have to create an object of Jar class by writing the syntax as follows:

Jar var2 = new Jar();

Then we can be able to invoke the function method3() of its Parent class Box by using syntax:

var2.method3();

in question it is given, Pill var2 = new Jar(); which is a Syntax error

iii) Third Error : Cup(var1).method1(); which is not possible to convert from parent object to child class object.

v ) Fifth Error is the Syntax Error because of the reason behind is that :

Since,

Object var5 = new Box(); is the wrong Syntax which should be modified as :

Box var5 = new Box();

Then Again var5.method3() should be invoked instead of (Pill)var5.method3();

Ans 4)

i) The Interface Incremental can be written as :

interface Incremental

{

public void increment();

public void decrement();

}

ii)

In Secretary class which implements Pay interface in order to define the body of the getRaise() method that must be declared as double because

getRaise() function is the member of the interface Pay which is declared with double return type. Hence it must also

be defined with double return type while defining the body of the same function in Secretary class.


Related Solutions

The question is as follows with all of the requirements commented in. /** * A class...
The question is as follows with all of the requirements commented in. /** * A class that represents a Hounsfield unit. Hounsfield units are the units of * measurement used in computed tomography (CT or CAT) scanning. * * <p> * The Hounsfield scale is defined by specifying the radiodensity of air as * {@code -1000} Hounsfield units and the radiodensity of distilled water as * {@code 0} Hounsfield units. Adjacent tissues in the human body can be * distinguished...
DO THIS IN C++: Question: Write a function “reverse” in your queue class (Codes are given...
DO THIS IN C++: Question: Write a function “reverse” in your queue class (Codes are given below. Use and modify them) that reverses the whole queue. In your driver file (main.cpp), create an integer queue, push some values in it, call the reverse function to reverse the queue and then print the queue. NOTE: A humble request, please don't just copy and paste the answer from chegg. I need more specific answer. Also I don't have much question remaining to...
Java Codes: 1. Create a class named Proficiency1Practice In the main method, first ask the user...
Java Codes: 1. Create a class named Proficiency1Practice In the main method, first ask the user to enter a short sentence which ends in a period. Use Java String class methods to determine the following about the sentence and display in the console: • How many total characters are in the sentence? • What is the first word of the sentence? Assume the words are separated by a space. • How many characters are in the first word of the...
Please finish the following JAVA Codes: 1. The class Person includes information of a person’s first...
Please finish the following JAVA Codes: 1. The class Person includes information of a person’s first name, last name, phone number, and email. Implement the class with appropriate constructors, getters and setters. 2. Derive a Student class that extends Person. In addition to a person’s information, a student has major, year, GPA, and a list of enrolled courses. In addition to appropriate constructors, getters and setters, make two methods addCourse and dropCourse. 3. Design and implement a program, either in...
Question 1 price is an instance variable of a class. Inside that class there is a...
Question 1 price is an instance variable of a class. Inside that class there is a method public void change(int price). From inside the method " change" how do we refer to the instance variable price and not the parameter price? Answer: Question 2 A method of a class can access which of the following: 1 global variables in the same scope 2. local variables defined within the method 3. the instance variables of its class 4. its parameters Question...
IN JAVA Question 1 The following classes along with the driver has been created and compiled....
IN JAVA Question 1 The following classes along with the driver has been created and compiled. public class Car { public void method1() { System.out.println("I am a car object"); } } class Point { public void method2() { System.out.println("I am a Point object"); } } class Animal { public void method3() { System.out.println("I am an animal object"); } } The following driver class has been created and all the lines of code inside the for loop is not compiling. Modify...
Essay question (1). 1. (10) We discussed R&D (research and development) as a driver of productivity...
Essay question (1). 1. (10) We discussed R&D (research and development) as a driver of productivity growth. In that context, we saw that intellectual property rights protection often is set to balance ex ante and ex post efficiency. a. Describe what is meant by ex ante and ex post efficiency in this context. How do the two perspectives on efficiency differ? b. What type of intellectual property rights protection is argued for from the ex ante efficiency perspective? From the...
Question No. 1 Accounting Error Avalanche Inc. purchased a machine on January 1, 2016, for $...
Question No. 1 Accounting Error Avalanche Inc. purchased a machine on January 1, 2016, for $ 1,100,000. At that time, it was estimated that the machine would have a 10-year life and no salvage value. On December 31, 2017, the controller found that the entry for depreciation expense had been omitted in 2016. The company uses the sum-of-the-years’- digits method for depreciating equipment. Required: Indicate how this event should be treated in the financial statements. Prepare the journal entry that...
This code is giving me an Assignment2.java:31: error: class, interface, or enum expected } ^ 1...
This code is giving me an Assignment2.java:31: error: class, interface, or enum expected } ^ 1 error and I don't know how to fix it. /*code bellow*/ import java.util.Scanner; import edhesive.assignment2.Airplane; import java.lang.Math.*; public class Assignment2{ public static void main(String[] args){    Airplane first=new Airplane("AAA01",1,0,0); Scanner scan=new Scanner(System.in); System.out.println("Enter the details of the second airplane (call-sign, distance, bearing and altitude):"); String cs=scan.nextLine(); double dist=scan.nextDouble(); int dir=scan.nextInt(); int alt=scan.nextInt(); Airplane second=new Airplane(cs.toUpperCase(),dist,dir,alt); System.out.println("\nInitial Positions:"); System.out.println("\"Airplane 1\": "+first+"\n\"Airplane 2\": "+second); System.out.println("The distance...
2.   Calculate Mean Absolute Error ( MAD) for the data in question 1 for the three    ...
2.   Calculate Mean Absolute Error ( MAD) for the data in question 1 for the three     methods used. Round MAD to two decimal places. ( 4 marks) Year Revenue 4-Year Moving Average Absolute Error 4 Weighted Moving Average Weights 4,3,2,1 Absolute Error    Exponential    Smoothing          α = 0.6 Absolute Error 2010 75 2011 81 2012 74 2013 79 2014 69 2015 92 2016 73 2017 85 2018 90 2019 73 2020 Forecast What does MAD measures? which of these...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT