Problems from the last few chapters
Tom Linton, Central College, COSC 135 A, Spring 03
- Give the Java code to declare a StringBuffer named buffy that contains
the text "StringBuffers are handy!".
- What Java code would have to follow your code from question 1, if you
wanted to change the contents of buffy by deleting the last character and
then add the text " for some things." to the end, and save the result in
buffy?
- In regards to the data class Money.java used in the chapter 4 programming
activity:
- What does the instance method below do?
public void funny(Money m)
{
this.cents = 4*m.getCents();
this.dollars = 4*m.getDollars() + (this.cents / 100);
this.cents = this.cents % 100;
}
- How would you declare an array called dailyBalances that contained
31 Money objects?
- Assuming part (b) has beed done, what does the code below accomplish?
dailyBalances[0] = new Money(500.0);
Money scratch, dep;
dep = new Money(50,0);
for (int day = 1; day < dailyBalances.length; day++) {
scratch = dailyBalances[day - 1].calculatePercent(0.06 / 365.0);
if (day % 7 == 5)
scratch = scratch.add( dep );
dailyBalances[day] = dailyBalances[day - 1].add( scratch );
}
- Use an array and loops to ask the user for a positive integer n (like
n = 3) and then ask them to enter n doubles, saving their entries in an array.
After they enter the n doubles, print them out in the opposite order that
they entered them (if they enter 1.0, 3.3, and 2.3, you'd print 2.3, 3.3,
1.0).
- Suppose a data class named GolfShot had 3 datafields. An int named
yards, to give the distance, in yards, of a golf shot. A String named club,
to hold the club used (like "putter", "driver", or "5-iron"), and a String
named result, to record the result of the shot (like "bad", "hit the green",
or "made the putt"). Write the Java code for this data class that declares
the datafields, implements a 3-parameter constructor (one parameter for each
datafield), and one accessor and one mutator method (you can select the datafield
to access or mutate).
- Consider the Java code below, that declares a method for some data
class:
public double silly(int n, String s)
- Does the method return a value? If so, what type of value is returned?
- If fred is an already declared and constructed object of this data
class, give a legal Java command, using literals like 4.3, true, or "Sampson"
as parameters, that calls the method and saves the result in a newly declared
variable.
- Given the Java code below, what value is stored in the variable n by
each Java fragment below?
int n;
int[][] table = new int[3][5];
for (int row = 0; row < table.length; row++)
for (int col = 0; col < table[row].length; col ++)
table[row][col] = 2*row + col;
- n = table.length;
- n = table[2][1];
- n = table[1].length;
- n = 0;
for (int i = 0; i < 5; i++)
n += table[1][i];
- n = 0;
for (int i = 0; i < 3; i++)
n += table[i][2];