Sunday, August 12, 2012

Arrays



Declare and instantiate an array named scores of twenty-five elements of type int .

int [] scores = new int [25];

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

Write a statement that declares an array named streetAddress that contains exactly  eighty  elements of type char .

char[] streetAddress = new char [80];
*********************************

Given that the array monthSales of integers has already been declared and that its elements contain sales data for the 12 months of the year in order (i.e., January, February, etc.), write a statement that writes to standard output the element corresponding to October.

Do not write anything else out to standard output. More...

System.out.println(monthSales[9]);

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

Given an array a , write an expression that refers to the first element of the array. More...

a [0]
********************************

Given an array a , declared to contain 34 elements, write an expression that refers to the last  element of the array.

a [33]
******************************

Given that an array named a with elements of type int has been declared, assign 3 to its  first element. More...

a [0] = 3;

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

Assume that an array named salarySteps whose elements are of type int and that has exactly five elements has already been declared.

Write a single statement to assign the value 30000 to the first element of this array.

salarySteps [0]= 30000;

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

Assume that an array of integers named salarySteps that contains exactly five elements has been declared.

Write a statement that assigns the value 160000 to the last element of the array salarySteps .


salarySteps [4]=160000;
***********************************

Assume that an array named a containing exactly 5 integers has been declared and initialized.

Write a single statement that adds 10 to the value stored in the first element of the array.

a [0] = a [0]+10;
**********************************

Assume that an array of int s named a has been declared with 12 elements. The integer variable k holds a value between 0 and 6 . Assign 15 to the array element whose index is k .

a [k]= 15;
*********************************

An array of int s named a has been declared with 12 elements. The integer variable k holds a value between 0 and 6 . Assign 9 to the element just after a[k] .

a [k+1] = 9;
**********************************

An array of int s named a has been declared with 12 elements. The integer variable k holds a value between 2 and 8 . Assign 22 to the element just before a[k] .

a [k-1] =22 ;
*******************************

Assume that an array of int s named a that contains exactly five elements has been declared and initialized. In addition, an int variable j has also been declared and initialized to a value somewhere between 0 and 3 .

Write a single statement that assigns a new value to element of the array indexed by j . This new value should be equal to twice the value stored in the next element of the array (i.e. the element after the element indexed by j .

a[j] = 2 * a[j+1] ;
**********************************

Given an array arr , of type int , along with two int variables i and j , write some code that swaps the values of arr[i] and arr[j] . Declare any additional variables as necessary.

int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

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

Given that an array of int s named a with 30 elements has been declared, assign 5 to its last element.

a[29] = 5 ;
************************************

Given that an array named a whose elements are of type int has been declared, assign the value
          -1
to the last element in a .

a[a.length-1] = -1 ;
************************************

Assume that the array arr has been declared. Write a statement that assigns the next to last   element of the array to the variable x , which has already been declared.

x = arr[arr.length-2] ;


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

Assume that an array of integers named a has been declared and initialized. Write a single statement that assigns a new value to the first element of the array. The new value should be equal to twice the value stored in the last element of the array.

a[0] = 2 * a[a.length-1] ;
************************************

Given an array of ints named x and an int variable named total that has already been declared, write some code that places the sum of all the elements of the array x into total. Declare any variables that you need.

total = 0 ;
for(int i = 0 ; i<x.length ; i++ )
{
total+= x [i];

}
**********************************

Given an array temps of double s, containing temperature data, compute the average temperature. Store the average in a variable called avgTemp . Besides temps and avgTemp , you may use only two other variables -- an int variable k and a double variable named total , which have been declared. More...

total = 0 ;
for( k = 0 ; k<temps.length ; k++ )
{
total = total + temps[k] ;
}
avgTemp = total/temps.length ;

************************************
We informally define the term corresponding element as follows:
The first element in an array and the last element of the array are corresponding elements.
Similarly, the second element and the element just before the last element are corresponding elements.
The third element and the element just before the element just before the last element are corresponding elements -- and so on.

Given an array a, write an expression for the corresponding element of a[i].     More...


a [ a . length - i - 1 ]
***********************************


Reversing the elements of an array involves swapping the corresponding elements of the array: the first with the last, the second with the next to the last, and so on, all the way to the middle of the array.

Given an array a and two other int variables, k and temp , write a loop that reverses the elements of the array.

Do not use any other variables besides a , k , and temp .


for( k=0 ; k<a.length/2 ; k++ )
{
temp = a[k] ;
a[k] = a[a.length - k - 1] ;
a[a.length - k - 1] = temp ;
}

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

Declare an array named a of   ten  elements of type int and initialize the elements (starting with the first) to the values 10 , 20 , ..., 100 respectively.

int a [] ={ 10,20,30,40,50,60,70,80,90,100};
********************************

Declare an array named taxRates of   five  elements of type double and initialize the elements (starting with the first) to the values 0.10 , 0.15 , 0.21 , 0.28 , 0.31 , respectively.

double [] taxRates = {0.10,0.15,0.21,0.28,0.31};
**********************************

Write a statement to declare and initialize an array named denominations that contains exactly six  elements of type of int .

Your declaration statement should initialize the elements of the array to the following values: 1 , 5 , 10 , 25 , 50 , 100 . (The value 1 goes into the first element, the value 100 to the last.)


int[] denominations = { 1 , 5 , 10 , 25 , 50 , 100 } ;
*********************************
Declare an array reference variable, week, and initialize it to an array containing the strings "mon", "tue", "wed", "thu", "fri", "sat", "sun" (in that order).

String[ ] week = {"mon", "tue", "wed", "thu", "fri", "sat", "sun" };
*********************************

printArray is a method that accepts one argument, an array of int s. The method prints the contents of the array; it does not return a value.

inventory is an array of int s that has been already declared and filled with values.

Write a statement that prints the contents of the array inventory by calling the method printArray .


printArray( inventory ) ;
*******************************

Write the definition of a method printArray , which has one parameter, an array of int s. The method does not return a value. The method prints out each element of the array, on a line by itself, in the order the elements appear in the array, and does not print anything else. More...

public void printArray( int[] s )
{
for ( int i = 0 ; i < s.length ; i++ )
{
System.out.println(s[i]) ;
}
}
**********************************

Write the definition of a method named sumArray that has one parameter, an array of int s. The method returns the sum of the elements of the array as an int .

public int sumArray ( int[] s )
{
int sum = 0 ;
for ( int i = 0 ; i < s.length ; i++ )
{
sum = sum + s[i] ;
}
return sum ;
}
************************************

Write the definition of a method, isReverse , whose two parameters are arrays of integers of equal size. The method returns true if and only if one array is the reverse of the other. ("Reverse" here means same elements but in reverse order.) More...

public boolean isReverse ( int[] a , int[] b )
{
if (a.length != b.length)
{
return false ;
}
for (int i = 0 ; i < a.length ; i++)
{
if (a[i] != b[b.length-1-i])
{
return false ;
}
}
return true ;
}
*************************************

Write the definition of a method reverse , whose parameter is an array of integers. The method reverses the elements of the array. The method does not return a value. More...

public void reverse ( int[] a )
{
for ( int i = 0 ; i < a.length/2 ; i++ )
{
int temp = a[i] ;
a[i] = a[a.length-i-1] ;
a[a.length-i-1] = temp ;
}
}
*************************************
Write a 'main' method that examines its command-line arguments and
calls the (static) method displayHelp if the only argument is the class name. Note that displayHelp accepts no parameters
otherwise, 'main' calls the (static) method argsError if the number of arguments is less than four.  argsError accepts the number of arguments (an integer) as its parameter
otherwise, 'main' calls the (static) method processArgs, which accepts the command-line argument array as its parameter.


public static void main(String[] args) {
if(args.length==1){ displayHelp();
}
else if(args.length < 4)
{argsError(args.length);
}
else {

processArgs(args);
}
}
*********************************

Given:
an int variable k ,
an int array currentMembers that has been declared and initialized,
an int variable memberID that has been initialized, and
an boolean variable isAMember ,
write code that assigns true to isAMember if the value of memberID can be found in currentMembers , and that assigns false to isAMember otherwise. Use only k , currentMembers , memberID , and isAMember .


for ( k=0 ; k<currentMembers.length ; k++ )
{
if (memberID==currentMembers[k])
{
isAMember = true ;
break ;
}
else
{
isAMember = false ;
}
}
************************************


An array of Strings, names, has been declared and initialized. Write the statements needed to determine whether any of the the array elements are null or refer to the empty String. Set the variable hasEmpty to true if any elements are null or empty-- otherwise set it to false.

hasEmpty = false;for (int i = 0; i < names.length; i++)if (names[i] == null || names[i].length() == 0)hasEmpty = true;
***********************************


You are given an int variable k , an int array zipcodeList that has been declared and initialized, and an boolean variable duplicates .

Write some code that assigns true to duplicates if there are two adjacent elements in the array that have the same value, and that assigns false to duplicates otherwise.
Use only k , zipcodeList , and duplicates . More...


duplicates = false ;

for( k=0 ; k<zipcodeList.length-1 ; k++ )
{
if (zipcodeList[k]==zipcodeList[k+1])
{
duplicates=true;
break ;
}
else
{
duplicates=false;
}
}
***********************************


You are given two int variables j and k , an int array zipcodeList that has been declared and initialized, and an boolean variable duplicates .

Write some code that assigns true to duplicates if any two elements in the array have the same value, and that assigns false to duplicates otherwise.
Use only j , k , zipcodeList , and duplicates . More...


duplicates = false ;

for( k=0 ; k<zipcodeList.length ; k++ )
{
for( j=k+1 ; j<zipcodeList.length ; j++ )
{
if (zipcodeList[k]==zipcodeList[j])
{
duplicates=true ;
}
}
}
************************************


An array of integers named parkingTickets has been declared and initialized to the number of parking tickets given out by the city police each day since the beginning of the current year. (Thus, the first element of the array contains the number of tickets given on January 1; the last element contains the number of tickets given today.)

A variable named mostTickets has been declared, along with a variable k .

Without using any additional variables, write some code that results in mostTickets containing the largest value found in parkingTickets .


mostTickets=0;
for(k=0;k<parkingTickets.length;k=k+1)
{
if (k==0)
{
mostTickets=parkingTickets[k];
}
if (parkingTickets[k]>mostTickets)
{
mostTickets=parkingTickets[k];
}
}
***********************************


Given
an int variable k ,
an int array incompletes that has been declared and initialized,
an int variable studentID that has been initialized, and
an int variable numberOfIncompletes ,
write code that counts the number of times the value of studentID appears in incompletes and assigns this value to numberOfIncompletes .

You may use only k , incompletes , studentID , and numberOfIncompletes .


numberOfIncompletes=0;
for(k=0;k<incompletes.length;k++)
{
if (studentID==incompletes[k])
{
numberOfIncompletes++ ;
}
}
*************************************
Declare a two-dimensional array of strings named chessboard.

String [][]chessboard;

****************************
Declare a two-dimensional array of integers named tictactoe.

int [][]tictactoe;
******************************
A 2-dimensional array of ints with 4 rows, has been created and assigned to a2d. Write an expression whose value is the total number of ints that could be stored in the entire array.

a2d[0].length + a2d[1].length + a2d[2].length + a2d[3].length
*******************************
A 2-dimensional array of ints, has been created and assigned to a2d. Write an expression whose value is the number of rows in this array.

a2d.length
*********************************
A 2-dimensional array of ints, has been created and assigned to a2d. Write an expression whose value is the number of elements in the last row. (Assume the array is not empty.)

a2d[a2d.length-1].length
***************************
A 2-dimensional array of ints, has been created and assigned to a2d. Write an expression whose value is the number of elements in the first row. (Assume the array is not empty.)

a2d[0].length
**************************
A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is true if the elements of any row or column or diagonal are equal.

tictactoe[0][0] == tictactoe[0][1] && tictactoe[0][0] == tictactoe[0][2]||tictactoe[1][0] == tictactoe[1][1] && tictactoe[1][0] == tictactoe[1][2]||tictactoe[2][0] == tictactoe[2][1] && tictactoe[2][0] == tictactoe[2][2]||tictactoe[0][0] == tictactoe[1][0] && tictactoe[0][0] == tictactoe[2][0]||tictactoe[0][1] == tictactoe[1][1] && tictactoe[0][1] == tictactoe[2][1]||tictactoe[0][2] == tictactoe[1][2] && tictactoe[0][2] == tictactoe[2][2]||tictactoe[0][0] == tictactoe[1][1] && tictactoe[0][0] == tictactoe[2][2]||tictactoe[0][2] == tictactoe[1][1] && tictactoe[0][2] == tictactoe[2][0]
***************************
A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is true if the elements of the diagonal that does NOT include the first element of the first row are all equal.

tictactoe[0][2] == tictactoe[1][1] && tictactoe[0][2] == tictactoe[2][0]
******************************
Assume you are given a boolean variable named isSquare and a 2-dimensional array that has has been created and assigned to a2d. Write some statements that assign true to isSquare if the entire 2-dimensional array is square meaning every row and column has the same number of elements as every other row and column.

isSquare = true ;

for (int i = 0 ; i < a2d.length; i++ ) {
if (a2d.length != a2d[i].length ) {isSquare = false ;}
}
*****************************
Assume you are given an int variable named sum and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that compute the sum of all the elements in the entire 2-dimensional array and assign the value to sum.

sum=0;
for (int i=0; i<a2d.length; i++)for (int j=0; j<a2d[i].length; j++)sum += a2d[i][j];

Wednesday, August 8, 2012

Exception Handling Basics

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 process throws any exception, your code prints the message "process failure" to standard output and does nothing else in regard to the exception.

try {
processor.process();
}
catch(Exception e) {
System.out.println("process failure");
}

*************************
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 you have class AutoFactory with two static methods called shutdown and reset. Neither method has any parameters. The shutdown; method may throw a ProductionInProgressException.

Write some code that invokes the shutdown method. If a ProductionInProgressException is thrown, your code should then invoke the reset method.

try {
AutoFactory.shutdown();
} catch (ProductionInProgressException pipe) {AutoFactory.reset();}

**************************
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.equals(""))
throw new Exception("empty command");
**********************************

Write a statement that throws a newly created Exception object whose message is "does not compute".

throw new Exception("does not compute");

*******************************
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 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");

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

Exception e;

********************************************
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()
************************************

Write a statement that declares a reference variable abend suitable for holding a reference to an Exception object and initialize it to an Exception object whose message is "ABEND 013".

Exception abend = new Exception("ABEND 013");

********************************************
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)

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

Assume that e is a variable of type Exception that has been declared and that references an Exception object. Write a statement that displays to standard output the message associated with e

System.out.println(e.getMessage());

******************************************
Assume that e is a variable of type Exception that has been declared and that references an Exception object. Assume that msg is a variable of type String. Write a statement that assigns to msg the message associated with e.

msg = e.getMessage();


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


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;
}
*******************************************

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;
}

**********************************************
The 'parseInt' method of the 'Integer' class throws a 'NumberFormatException' when it is passed a String argument that it cannot convert to an int. Given the String variable s (which has already been assigned a value), write the code needed to convert the value in s assigning the result to the integer variable i

If a NumberFormatException is thrown, i should be assigned the value -1.

try {
i = Integer.parseInt(s);
} catch (NumberFormatException e) { i = -1;}

*****************************
Write a statement that throws an IOException with the customized message "really BAD data".

throw new IOException("really BAD data");



Write the definition of a class named PanicException that has no associated message (i.e. null).

public class PanicException extends Exception {
}
******************************
Write the definition of a class named PanicException that supports the specification of a message. In addition, this version of PanicException arranges for the string "PANIC! " appears before the message. And if a PanicException is instantiated without an argument, its associated message will simply be "PANIC!".

public class PanicException extends Exception {
public PanicException() {
super("PANIC!");
}
public PanicException(String msg) {
super("PANIC! "+msg);
}
}
************************************
The argument to a square root method (sqrt) in general should not be negative. Write the definition of a class named SQRTException whose objects are created by specifying the original negative value that caused the problem in the first place: new SQRTException(originalArgument). The associated message for this Exception should be "Bad argument to sqrt: " followed by the value specified at the time of instantiation.

public class SQRTException extends Exception {
public SQRTException(double badvalue) {
super("Bad argument to sqrt: " + badvalue);
}
}
****************************************
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 nfe) {
System.out.println("Bad Data");
}
catch(FileNotFoundException fnfe) {
System.out.println("Data File Missing");
}
catch(Exception e) {
System.out.println(e.getMessage());
}

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



Inheritance Basics



Assume the existence of a BankAccount class.

Define a subclass, SavingsAccount that contains the following:
a double instance variable, interestRate
a constructor that accepts a parameter of type double which is used to initialize the instance variable


public class SavingsAccount extends BankAccount{
private double interestRate;
public SavingsAccount(double interestRate) {
this.interestRate = interestRate;
}
}


Assume the existence of a Phone class. Define a subclass, CameraPhone that contains two instance variables: an integer named, imageSize, representing the size in megapixels (for simplicity assume a pixel takes up one byte-- thus megapixels equals megabytes) of each picture (i.e., 2 means each image is composed of 2 megapixels), and an integer named memorySize, representing the number of gigabytes in the camera's memory (i.e., 4 means 4 Gigabyes of memory). There is a constructor that accepts two integer parameters corresponding to the above two instance variables and which are used to initialize the respective instance variables. There is also a method named numPictures that returns (as an integer) the number of pictures the camera's memory can hold. Don't forget that a gigabyte is 1,000 megabytes.


public class CameraPhone extends Phone { public CameraPhone(int imageSize, int memorySize) { this.imageSize = imageSize; this.memorySize = memorySize; } public int numPictures() {return memorySize * 1000 / imageSize;} private int imageSize; private int memorySize;}


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
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 you have a class Square. This class has an instance variable, side that is protected and of type double.

Write the class definition of a subclass of Square called FancySquare that has a method called getDiagonal. The getDiagonal method gets no arguments but returns the value of side multiplied by the square root of two.

class FancySquare extends Square {                double getDiagonal() {return side*Math.sqrt(2.0);}            }



The superclass Calculator contains:
a (protected) double instance variable, accumulator, that contains the current value of the calculator.
write a subclass, CalculatorWithMemory, that contains:
a double instance variable, memory, initialized to 0
a method, save, that assigns the value of accumulator to memory
a method, recall, that assigns the value of memory to accumulator
a method, clearMemory, that assigns zero to memory
a method, getMemory, that returns the value stored in memory


public class CalculatorWithMemory extends Calculator {
public void save() {memory = accumulator;}
public void recall() {accumulator = memory;}
public void clearMemory() {memory = 0;}
public double getMemory() {return memory;}
private double memory;
}



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.


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



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.


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



A Color class has three public accessor methods: getRed, getGreen, getBlue, that return that value (integer) of the corresponding color component for that color.
The class AlphaChannelColor-- a subclass of Color-- has a default constructor.
Declare a variable of type AlphaChannelColor and initialize it to an AlphaChannelColor object created using the default constructor. Send the values of the red, green, and blue components (in that order and separated by spaces) to System.out


AlphaChannelColor acc = new AlphaChannelColor();System.out.println(acc.getRed() + " " + acc.getGreen() + " " + acc.getBlue());



A Color class has three public, integer-returning accessor methods: getRed, getGreen, and getBlue, and three protected, void-returning mutator methods: setRed, setGreen, setBlue, each of which accepts an integer parameter and assigns it to the corresponding color component.
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. AlphaChannelColor also has a method named dissolve (void-returning, and no parameters), that causes the color to fade a bit. It does this by incrementing (by 1) all three color components (using the above accessor and mutator methods) as well as the alpha component value.
Write the dissolve method.

public void dissolve() { setRed(getRed()+1); setGreen(getGreen()+1); setBlue(getBlue()+1); alpha++;}



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, ICalculator3, based on ICalculator. The class ICalculator3 overrides the div method of ICalculator. It checks its argument and if the argument is zero, it prints to standard output the message "ZERO DIVIDE ATTEMPT" and simply returns the value of currentValue. Otherwise, if the argument is NOT zero, the method invokes the base class method div (from ICalculator) and returns the value that it receives from that call.


public class ICalculator3 extends ICalculator {    public int div(int x) {        if (x!=0) return super.div(x);        System.out.println("ZERO DIVIDE ATTEMPTED");        return getCurrentValue();    }}


The superclass, EducationalInstitution, contains:
an int instance variable, duration, indicating the standard number of years spent at the institution
A constructor that accepts an int which is used to initialize the duration instance variable
a method graduationRequirements that returns a String. The (default) behavior of graduationRequirements is to return a String stating "d years of study", where d is the value of the duration instance variable
Write a class definition for the subclass LawSchool that contains:
a (default) constructor that invokes the superclass constructor with the value 3 (law school is typically a three year program).
a (overridden) method graduationRequirements that returns the string "3 years of study and passing the bar". You MUST invoke the graduationRequirements method of the superclass in this method (to obtain the first portion of the resulting string).


class LawSchool extends EducationalInstitution {                LawSchool() {super(3);}                String graduationRequirements() {return super.graduationRequirements() + " and passing the bar";}            }




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 name = super.getColorName(); if (name == null) name = "color"; if (alpha < 100) return "opaque " + name; else if (alpha < 200) return "semi-transparent " + name; return "transparent " + name;}



Assume the existence of a BankAccount class with a method, getAvailable that returns the amount of available funcs 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 funcds 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;}



Assume the existence of a Window class with a method getClientAreaHeight that returns an integer representing the height of the portion of the window that an application program can use for its display. Assume also, a subclass BorderedWindow with an integer instance variable borderSizeh, that represents the size of the border around the window. Override the getClientAreaHeight in BorderWindow to return the client area height as returned by the superclass minus the border size (taking into account top and bottom borders).


public int getClientAreaHeight() {return super.getClientAreaHeight() - 2 * borderSize;}


Assume the existence of a Phone class with a method, clear, that clears the phone's memory-- its phone book, list of call, text messages, etc. Assume also, a subclass CameraPhone with an instance variable, album, of type PhotoAlbum-- which has a method, also called clear that clears its contents. Override the clear method in CameraPhone to clear the entire phone, i.e., to invoke the clear method of Phone (the superclass), as well as invoking the clear method of the album instance variable.


public void clear() { super.clear(); album.clear();}


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.


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


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 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;}


Assume the existence of a Window class with a constructor that accepts two integer parameters containing the width and height of the window (in that order).
Assume a subclass TitledWindow has been defined that has two instance variables:
a string named text for the text of the title and,
an integer, titleBarHeight for the height of the title bar. Write a constructor for TitledWindow that accepts four parameters:
two integers containing the width and height (which are passed up to the Window constructor), and,
a string and integer which are used to initialize the TitledWindow instance variables. The height of the title bar should be 'clamped' by the constructor to one half the height of the window-- i.e., if the height of the title bar passed into the constructor is greater than one half the specified height of the window, it should be set to one half the height of the window.


TitledWindow(int width, int height, String text, int titleBarHeight) { super(width, height); this.text = text; if (titleBarHeight > height / 2) titleBarHeight = height / 2; this.titleBarHeight = titleBarHeight;}



Assume the existence of a Phone class with a constructor that accepts two parameters: a string for the phone number followed by a boolean representing whether the phone provides added-value services. Assume a subclass MP3Phone has been defined that has two instance variables: an integer, memorySize, for the size, in megabytes of the phone memory, and a boolean, playsAAC, representing whether the phone is capable of playing AAC-encoded audio files. Write a constructor for MP3Phone that accepts three parameters: a String for the phone number (which is passed up to the Phone constructor, together with the value true for the added-value boolean), and an integer followed by a boolean for the instance variables.


MP3Phone(String phoneNumber, int memorySize, boolean playsAAC) { super(phoneNumber, true); this.memorySize = memorySize; this.playsAAC = playsAAC;}


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 + ")";}



Write a class named Book containing:
Two instance variables named title and author of type String.
A constructor that accepts two String parameters. The value of the first is used to initialize the value of title and the value of the second is used to initialize author .
A method named toString that accepts no parameters. toString returns a String consisting of the value of title , followed by a newline character, followed by the value of author .


public class Book
{
private String title;
private String author;
public Book (String title, String author)
{
this.title = title;
this.author = author;
}
public String toString()
{
return title+ "\n" + author;
}
}



Write a class named Book containing:
Three instance variables named title, author, and tableOfContents of type String. The value of tableOfContents should be initialized to the empty string.
An instance variable named nextPage of type int, initialized to 1.
A constructor that accepts two String parameters. The value of the first is used to initialize the value of title and the value of the second is used to initialize author.
A method named addChapter that accepts two parameters. The first, of type String, is the title of the chapter; the second, is an integer containing the number of pages in the chapter. addChapter appends (that is concatenates) a newline followed by the chapter title followed by the string "..." followed by the value of the nextPage instance variable to the tableOfContents. The method also increases the value of nextPage by the number of pages in the chapter.
A method named getPages that accepts no parameters. getPages returns the number of pages in the book.
A method named getTableOfContents that accepts no parameters. getTableOfContents returns the values of the tableOfContents instance variable.
A method named toString that accepts no parameters. toString returns a String consisting of the value of title, followed by a newline character, followed by the value of author.

public class Book{
private String title;
private String author;
private String tableOfContents = "";
private int nextPage = 1;
public Book (String a , String b){
this.title = a;
this.author = b;
}
public void addChapter (String chapterTitle, int number){
tableOfContents += "\n" + chapterTitle + "..." + nextPage;
nextPage += number;
}
public int getPages(){
return nextPage-1;
}
public String getTableOfContents(){
return tableOfContents;
}
public String toString(){
return title + "\n" + author;
}
}





Sunday, August 5, 2012

Gum balls and Candy bars coupons in Java

/*
* Description: Write a program that defines a variable initially
* assigned to the number of coupons you win.
* Then , The program should output how many candy bars and gum balls
* you can get if you spend all of your coupons on candy bars first,
* and remaining coupons on gum balls.
*/
public class Coupons {


public static void main(String[] args) {

// Declare a variable indicating the Number of Tickets you won.
int numberoftickets;
numberoftickets = 49;
// Declare a variable indicating the number of Candy Bars you
//can get from the tickets you have
int candybars;
candybars = (numberoftickets/10);
//Declare a variable indicating the numbers of the left tickets.
int lefttickets;
lefttickets = (numberoftickets%10);
//Declare a variable indicating the numebr of gum balls you can get from the left tickets.
int gumballs;
gumballs = (lefttickets/3);

// use the println command to write the number of candybars and gumbballs you can get.
System.out.println("The Total Number of Candy Bars is = " + candybars);
System.out.println("The Total Number of Gum Balls is = " + gumballs);

}
//end.

}

STATISTICS 381 Quizzes 1,2,3,4,5,6










Calculus Three (III) Exam 3 - Math 209



All Quizzes Calculus Three (III) - Math 209























Calculus Three (III) EXAM 3 ,Math 209



Calculus Three (III) EXAM 2 ,Math 209



Calculus Three (III) EXAM 2 B ,Math 209