CSCI 369 - Exam 3 (Code Lab)

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Write a statement that declares a reference variable e suitable for holding a reference to an Exception object .

Exception e;

Declare a reference variable of type File named myFile

File myFile;

Assume the availability of class named DataTransmitter that provides a static method , sendSignal that takes no arguments . Write the code for invoking this method .

DataTransmitter.sendSignal();

Assume the availability of class named DateManager that provides a static method , printTodaysDate , that accepts no arguments and returns no value . Write a statement that calls printTodaysDate .

DateManager.printTodaysDate();

Declare a variable named myMenu suitable for holding references to Menu objects

Menu myMenu;

Assume the existence of a Window class with methods getWidth and getHeight, and a subclass TitledWindow, with a constructor accepts a string corresponding to the title of the window. Declare a variable , tWindow, of type TitledWindow variable , and initialize it to a TitledWindow object with a title of "My Title". Print out the width and height of the window (in that order) separated by a space.window (in that order) separated by a space.

TitledWindow tWindow = new TitledWindow("My Title"); System.out.println(tWindow.getWidth() + " " + tWindow.getHeight());

Write the definitions of two classes Day and Night. Both classes have no constructors, methods or instance variables. Note: For this exercise, please do not declare your classes using the public visibility modifier.

class Day{} class Night {}

Assume the availability of class named IMath that provides a static method , toThePowerOf is a method that accepts two int arguments and returns the value of the first parameter raised to the power of the second. An int variable cubeSide has already been declared and initialized . Another int variable , cubeVolume, has already been declared . Write a statement that calls toThePowerOf to compute the value of cubeSide raised to the power of 3 and that stores this value in cubeVolume.

cubeVolume = IMath.toThePowerOf(cubeSide, 3);

Assume the availability of a class named Arithmetic that provides a static method , add , that accepts two int arguments and returns their sum . Two int variables , euroSales and asiaSales , have already been declared and initialized . Another int variable , eurasiaSales , has already been declared . Write a statement that calls add to compute the sum of euroSales and asiaSales and that stores this value in eurasiaSales

eurasiaSales = Arithmetic.add(euroSales, asiaSales);

Assume that command is a variable of type String . Write a statement that throws an Exception with a message "null command" if command is null and that throws an Exception with a message "empty command" if command equals the empty string .

if (command == null) { throw new Exception("null command"); } else if (command == "") { throw new Exception("empty command"); }

Assume that command is a variable of type String . Write a statement that throws an Exception with a message "null command" if command is null.

if(command==null){ throw new Exception("null command"); }

Assume that logger is a reference to an object that has a method named printLarger that accepts two int arguments and returns no value . Two int variables , sales1 and sales2 , have already been declared and initialized . Write a statement that calls printLarger , passing it sales1 and sales2 .

logger.printLarger(sales1, sales2);

`Suppose a reference variable of type Double called myDouble is already declared . Create an object of type Double with the initial value of 1.5 and assign it to the reference variable myDouble .

myDouble = new Double(1.5);

Suppose a reference variable of type Integer called myInt is already declared . Create an object of type Integer with the initial value of 1 and assign it to the reference variable myInt .

myInt = new Integer(1);

Suppose a reference variable of type Long called myLong is already declared . Create an object of type Long with the initial value of two billion and assign it to the reference variable myLong .

myLong = new Long(2000000000);

Assume that maxtries is a variable of type int that has been declared and given a value . Write an expression whose value is a reference to a newly created Exception object whose message is the string "attempt limit exceeded: " followed by the value of maxtries.

new Exception("attempt limit exceeded: "+maxtries)

Write an expression whose value is a reference to a newly created Exception object whose message is "out of oil".

new Exception("out of oil")

Write an expression whose value is a reference to a newly created Exception object with no specific message .

new Exception()

Assume the existence of a Building class with a constructor that accepts two parameters : a reference to an Address object representing the building's address, and an integer for the square footage of the building. Assume a subclass ApartmentBuilding has been defined with a single integer instance variable , totalUnits. Write a constructor for ApartmentBuilding that accepts three parameters : an Address and an integer to be passed up to the Building constructor , and an integer used to initialize the totalUnits instance variable .

public ApartmentBuilding(Address address, int squareFootage, int totalUnits) { super(address, squareFootage); this.totalUnits = totalUnits; }

A class named Clock has two instance variables: hours (type int ) and isTicking (type boolean). Write a constructor that takes a reference to an existing Clock object as a parameter and copies that object's instance variables to the object being created. Your task: Write a Clock constructor that makes this possible. Just write this constructor -- don't write the whole class or any code outside of the class!

public Clock (Clock c) { hours = c.hours; isTicking = c.isTicking; }

You are given a class named Clock that has three instance variables : One of type int called hours, another of type boolean called isTicking, and the last one of type Integer called diff. Write a constructor for the class Clock that takes three parameters -- an int , a boolean , and another int . The constructor should set the instance variables to the values provided.

public Clock (int hours, boolean isTicking, int diff){ this.hours = hours; this.isTicking = isTicking; this.diff = new Integer (diff); }

You are given a class named Clock that has one int instance variable called hours. Write a constructor with no parameters for the class Clock. The constructor should set hours to 12.

public Clock() { hours = 12; }

Assume the existence of a BankAccount class with a constructor that accepts two parameters : a string for the account holder's name , followed by an integer for the account number. Assume a subclass SavingsAccount has been defined with a double instance variable named interestRate. Write a constructor for SavingsAccount that accepts three parameters (in the following order): a string and an integer that are passed to the constructor of BankAccount, and a double that is used to initialize the instance variable .

public SavingsAccount(String name, int socSecNum, double interestRate) { super(name, socSecNum); this.interestRate = interestRate; }

A Color class has a method getColorName that returns a string corresponding to the common name for the color, e.g., yellow, blue, white, etc. If there is no common name associated with the color, null is returned. The class , AlphaChannelColor-- a subclass of Color-- has an integer instance variable , alpha, containing the alpha channel value , representing the degree of transparency of the color. Write the method getColorName of AlphaChannelColor, that overrides the method in the Color class . AlphaChannelColor's getColorName should return the name of the color (obtained from the getColorName method of Color) prefixed with the word 'opaque' if the alpha value is less than 100, 'semi-transparent' if the alpha value is otherwise less than 200, and 'transparent' otherwise (separate the prefix from the color name by a blank). If the color has no name , the method should return "opaque color", "semi-transparent color", or "transparent color", according the the same alpha values as above.

public String getColorName() { String s; if (alpha < 100) s = "opaque"; else if (alpha < 200) s = "semi-transparent"; else s = "transparent"; if (super.getColorName() == null) return s + " color"; else return s + " " + super.getColorName(); }

Write a method max that has two string parameters and returns the larger of the two.

public String max (String aString, String bString) { if (aString.compareTo(bString) > 0) { return aString; } else { return bString; } }

Write a method min that has three string parameters and returns the smallest.

public String min (String aString, String bString, String cString) { if (aString.compareTo(bString) < 0 && aString.compareTo(cString) < 0) { return aString; } else if (bString.compareTo(cString) < 0 && bString.compareTo(aString) < 0) { return bString; } else { return cString; } }

A Color class has three integer color component instance variable : red, green, and blue. Write a toString method for this class . It should return a string consisting of the three color components (in the order red, green, blue) within parentheses, separated by commas, with a '#' prefix e.g. #(125, 30, 210)

public String toString() { return "#(" + red + "," + green + "," + blue + ")"; }

Assume the existence of a Window class with integer instance variables width, height, xPos and yPos. Define the method toString for the Window class . The String representation of a Window object should be of the form "A 'width'x'height' window at ('xPos','yPos')" where the values within the "'s are replaced by the actual values of the corresponding instance variables . For example, given a Window object whose width is 80, height is 20, xPos is 0 and yPos is 30, toString should return "A 80×20 window at (0,30)"

public String toString() { return "A " + width + "x" + height + " window at (" + xPos + "," + yPos + ")"; }

Write a class named Acc1 containing no constructors, methods, or instance variables. (Note, the last character or the classname is "one" not "ell".)

public class Acc1{}

A Color class has a constructor that accepts three integer parameters : red, green and blue components in the range of 0 ... 255 with 0 representing no contribution of the component and 255 being the most intense value for that component . The effect of full or semi-transparency can be achieved by adding another component to the color called an alpha channel. This value can also be defined to be in the range of 0...255 with 0 representing opaque or totally non-transparent, and 255 representing full transparency. Define a class AlphaChannelColor to be a subclass of the Color class . AlphaChannelColor should have the following: - an integer instance variable alpha - a constructor that accepts four parameters : red, green, blue and alpha values in that order. The first three should be passed up to the Color class ' constructor , and the alpha value should be used to initialize the alpha instance variable . - a getter (accessor) method for the alpha instance variable

public class AlphaChannelColor extends Color { public AlphaChannelColor(int red, int green, int blue, int alpha) { super(red, green, blue); this.alpha = alpha; } public int getAlpha() {return alpha;} private int alpha; }

Given an existing class , BankAccount, containing: a constructor accepting a String corresponding to the name of the account holder. a method , getBalance, that returns a double corresponding to the account balance. a method withdraw that accepts a double , and deducts the amount from the account balance. Write a class definition for a subclass, CheckingAccount, that contains: a boolean instance variable , overdraft. (Having overdraft for a checking account allows one to write checks larger than the current balance). a constructor that accepts a String and a boolean . The String parameter is used in the invocation of the superclass (BankAccount) constructor , while the boolean is used to initialize the overdraft instance variable. A method , hasOverdraft, that returns a boolean. hasOverdraft returns true if the account supports overdraft. a method, clearCheck, that accepts a double and returns a boolean . clearCheck will determine if the amount (of the check) can be cashed-- this will be the case if the amount is less than the balance in the account, or if the account allows overdraft. If the check can be cashed, clearCheck returns true , and also calls the withdraw method to update the account balance; otherwise, clearCheck returns false .

public class CheckingAccount extends BankAccount { public CheckingAccount(String name, boolean overdraft) { super(name); this.overdraft = overdraft; } public boolean hasOverdraft() { return overdraft; } public boolean clearCheck(double amount) { if (getBalance() >= amount || overdraft) { withdraw(amount); return true; } return false; } private boolean overdraft; }

Write the definition of a class Clock. The class has no constructors and two instance variables . One is of type int called hours and the other is of type boolean called isTicking.

public class Clock { private int hours; private boolean isTicking; }

Write the definition of a public class Clock. The class has no constructors and one instance variable of type int called hours.

public class Clock { private int hours; }

Write the definition of a class ContestResult containing: An instance variable winner of type String , initialized to the empty String . An instance variable secondPlace of type String , initialized to the empty String . An instance variable thirdPlace of type String , initialized to the empty String . A method called setWinner that has one parameter , whose value it assigns to the instance variable winner. A method called setSecondPlace that has one parameter , whose value it assigns to the instance variable secondPlace. A method called setThirdPlace that has one parameter , whose value it assigns to the instance variable thirdPlace. A method called getWinner that has no parameters and that returns the value of the instance variable winner. A method called getSecondPlace that has no parameters and that returns the value of the instance variable secondPlace. A method called getThirdPlace that has no parameters and that returns the value of the instance variable thirdPlace. No constructor need be defined.

public class ContestResult{ private String winner = ""; private String secondPlace = ""; private String thirdPlace = ""; public void setWinner(String win){ winner = win; } public void setSecondPlace(String second){ secondPlace = second; } public void setThirdPlace(String third){ thirdPlace = third; } public String getWinner(){ return winner; } public String getSecondPlace(){ return secondPlace; } public String getThirdPlace(){ return thirdPlace; } }

The superclass Student contains: a constructor that accepts a String corresponding to the name of the school the student attends a toString method that returns 'student at X' where X is the name of the school the student attends. Write a class definition for the subclass HighSchoolStudent containing: a constructor accepting a String which is used as a parameter to the superclass constructor a toString method that returns 'high school student at X'. This method must use the toString method of its superclass.

public class HighSchoolStudent extends Student { public HighSchoolStudent(String s) { super(s); } public String toString() { return "high school " + super.toString(); } }

Assume the availability of an existing class , ICalculator, that models an integer arithmetic calculator and contains: an instance variable currentValue that stores the current int value of the calculator a getter method for the above instance variable methods add, sub, mul, and div Each method in ICalculator receives an int argument and applies its operation to currentValue and returns the new value of currentValue. So, if currentValue has the value 8 and sub(6) is invoked then currentValue ends up with the value 2, and 2 is returned. So, you are to write the definition of a subclass, ICalculator1, based on ICalculator. The class ICalculator1 has one additional method , sign, that receives no arguments , and doesn't modify currentValue. Instead, it simply returns 1, 0 or -1 depending on the whether currentValue is positive, zero, or negative respectively.

public class ICalculator1 extends ICalculator { public int sign() { return Integer.signum(getCurrentValue()); } }

Assume the availability of an existing class , ICalculator, that models an integer arithmetic calculator and contains: an instance variable currentValue that stores the current int value of the calculator and can be accessed and modified by any subclass. methods add, sub, mul, and div Each method in ICalculator receives an int argument and applies its operation to currentValue and returns the new value of currentValue. So, if currentValue has the value 8 and sub(6) is invoked then currentValue ends up with the value 2, and 2 is returned. So, you are to write the definition of a subclass, ICalculator2, based on ICalculator. The class ICalculator2 has one additional method , negate, that receives no arguments . The effect of negate is to reverse the sign of currentValue. For example, if currentValue is zero, there is no change, if it is -22 then it becomes 22, if it is 100 it becomes -100. Furthermore negate returns the new value of currentValue.

public class ICalculator2 extends ICalculator { public int negate() { currentValue = -currentValue; return currentValue; } }

Write the definition of a class Player containing: An instance variable name of type String , initialized to the empty String . An instance variable score of type int , initialized to zero. A method called setName that has one parameter , whose value it assigns to the instance variable name . A method called setScore that has one parameter , whose value it assigns to the instance variable score. A method called getName that has no parameters and that returns the value of the instance variable name . A method called getScore that has no parameters and that returns the value of the instance variable score. No constructor need be defined.

public class Player{ private String name = ""; private int score = 0; public void setName(String nm){ name = nm; } public void setScore(int sc){ score = sc; } public String getName(){ return name; } public int getScore(){ return score; } }

Write the definition of a class Simple. The class has no constructors, methods or instance variables.

public class Simple{}

Write the definition of a class WeatherForecast that provides the following behavior (methods ): A method called setSkies that has one parameter , a String . A method called setHigh that has one parameter , an int . A method called setLow that has one parameter , an int . A method called getSkies that has no parameters and that returns the value that was last used as an argument in setSkies. A method called getHigh that has no parameters and that returns the value that was last used as an argument in setHigh. A method called getLow that has no parameters and that returns the value that was last used as an argument in setLow. No constructor need be defined. Be sure to define instance variables as needed by your "get"/"set" methods -- initialize all numeric variables to 0 and any String variables to the empty string .

public class WeatherForecast{ private String skies = ""; private int high = 0; private int low = 0; public void setSkies(String theSkies){ skies = theSkies; } public void setHigh(int theHigh){ high = theHigh; } public void setLow(int theLow){ low = theLow; } public String getSkies(){ return skies; } public int getHigh(){ return high; } public int getLow(){ return low; } }

Assume the existence of a BankAccount class with a method , getAvailable that returns the amount of available funds in the account (as an integer ), and a subclass, OverdraftedAccount, with two integer instance variables : overdraftLimit that represents the amount of money the account holder can borrow from the account (i.e., the amount the account balance can go negative), and overdraftAmount, the amount of money already borrowed against the account. Override the getAvailable method in OverdraftedAccount to return the amount of funds available (as returned by the getAvailable method of the BankAccount class ) plus the overdraftLimit minus the overdraftAmount.

public int getAvailable() { return super.getAvailable() + (overdraftLimit - overdraftAmount); }

Many city ordinances have a requirement that buildings be surrounded by a certain amount of empty space for sunlight and fresh air. Apartment buildings-- begin residences and in particular multiple dwelling, usually have higher requirements than commercial or single residence properties. These requirements are often based upon square footage, number of occupants, etc. Assume the existence of a class Building with a method getRequiredEmptySpace that returns the amount of empty space (as an integer representing square feet) for the building. Asume further, a subclass, ApartmentBuilding, with two integer instance variables : totalUnits representing the number of apartments in the building and maxOccupantsPerUnit, represents the maximum number of people allowed in each unit, by law. Override getRequiredEmptySpace in ApartmentBuilding to reflect the fact that apartment buildings require an addition square foot of empty space around it for each potential person living in the building.

public int getRequiredEmptySpace() { return super.getRequiredEmptySpace() + totalUnits * maxOccupantsPerUnit; }

The method shown below, makeJunk generates compile-time error: "unreported exception java.io.IOException; must be caught or declared to be thrown". Without changing the behavior (any part of the method body ) and without changing the number of arguments the function takes or its visibility, add the necessary code that will permit this code to compile without error.

public void makeJunk() throws IOException { new File("junk").createNewFile(); }

Assume that success is a variable of type boolean that has been declared. Assume that processor refers to an object that provides a void method named process that takes no arguments. As it happens, the process method may throw one of several exceptions. Write some code that invokes the process method provided by the object associated with processor and arrange matters so that if any exception is thrown success to be set to false but otherwise it is set to true.

success = true; try { processor.process(); } catch (Exception e) { success = false; }

Assume that dataFailure is a variable of type Exception that has been declared and that references an Exception object . Write a statement that throws that Exception object .

throw dataFailure;

Assume that processor refers to an object that provides a void method named process that takes no arguments . As it happens, the process method may throw one of several exceptions. One of these is NumberFormatException, another is FileNotFoundException. And there are others. Write some code that invokes the process method provided by the object associated with processor and arranges matters so that if a NumberFormatException is thrown, the message "Bad Data" is printed to standard output , and if FileNotFoundException. is thrown, the message "Data File Missing" is printed to standard output . If some other Exception is thrown, its associated message is printed out to standard output .

try { processor.process(); } catch (NumberFormatException ne) { System.out.println("Bad Data"); } catch (FileNotFoundException fe) { System.out.println("Data File Missing"); } catch (Exception e) { System.out.println(e.getMessage()); }

Assume that processor refers to an object that provides a void method named process that takes no arguments. As it happens, the process method may throw one of several exceptions. Write some code that invokes the process method provided by the object associated with processor and arrange matters so that your code causes any exception thrown by process to be ignored.

try { processor.process(); } catch(Exception e) { // just ignore the exception }

Assume that validData is a variable of type boolean that has been declared. Assume that processor refers to an object that provides a void method named process that takes no arguments. As it happens, the process method may throw one of several exceptions, one of which is NumberFormatException. Write some code that invokes the process method provided by the object associated with processor and arrange matters so that any NumberFormatException that is thrown is caught and causes validData to be set to false.

try { processor.process(); } catch(NumberFormatException nfe) { validData=false; }


Ensembles d'études connexes

NCLEX PN content area /pharmacology

View Set

IB French B text types vocabulary: La lettre/le courreil (letter/email)

View Set

Chapter 5 Quiz: Thinking & Intelligence

View Set