function:RenderSidePart pageleftbodycaption pageleftbody sidenote Main.StudyGuideForChapter2-SideNote Main.SideNote Site.SideNote

# 2.1 Variables; Arithmetic, Relational, and Logical Operators

Computers use base 2, not base 10, like most humans. Take a look at Bits And Bytes or The binary game

In base 10, {$\frac{1}{3}$} has issues..... 0.33333333333 is only approximately equal to {$\frac{1}{3}$} -- to be exact, there shouldn't be an end to those repeating 3's. There is similar trouble in all bases, even base two. Try 4.35*100 for example....shouldn't that be 435.0? Try it.... Use the BlueJ code pad to and experiment-- can you see the trouble? Can you find another?

There are other simple data types in java like the int, but smaller. The byte type is an integer that only takes 8 bits (1 byte=8 bits). In the BlueJ code pad, try this:

byte x=127;
x+1


Isn't 127+1=128? What does your poor computer think it is? This is an overflow of the poor byte.

{$2^7-1=127$} so thats why there is a problem.

The short is 2 bytes (or 16 bits) so it has trouble adding 1 to 32767 (Since {$2^{15}-1=32767$} ) You can compute this using the Math.pow() method:

(short)( Math.pow(2,15)-1 )


Use the code pad to try an overflow of a short.

The int is 4 bytes (or 32 bits). How big a number can fit into an int? Try to overflow an int!

Once in a wile, even big companies like Intel can make mistakes. The Pentium processor had a famous blunder.

{$\left(\frac{4195835}{3145727}\right) \left(\frac{3145727}{1} \right) - 4195835 = 0$}, right? Shouldn't those 3145727's cancel, leaving 4195835-4195835=0? Well, according to a pentium FP, it's 256 not 0! Try it in your BlueJ code pad.... is it fixed now?

• R2.1.1 Implement a class QuadraticEquation (you can start with the code below if you wish to save time) whose constructor receives the coefficients a, b, c of the quadratic equation ax2 + bx + c = 0. Supply methods getSolution1 and getSolution2 that get the solutions, using the quadratic formula. Write a test class QuadraticEquationTester (or use the sample one below if you wish) that constructs a QuadraticEquation object, and prints the two solutions. For example, if you make QuadraticEquation myProblem = new QuadraticEquation(2,5,-3), the solutions should be .5 and -3

Recall that if {$ax^2+bx+c=0$} then {$x= \frac{-b \pm \sqrt{b^2-4ac}}{2a}$}

public class QuadraticEquationTester
{
public static void main(String[] args)
{
double x1 = myProblem.getSolution1();
double x2 = myProblem.getSolution2();
System.out.println(myProblem);
System.out.println("The solutions are "+x1+" and "+x2);
System.out.println("Expected .5 and -3");
}
}


public class QuadraticEquation
{

private double a,b,c;

public  QuadraticEquation (double theA, double theB, double theC )
{
a=theA;
b=theB;
c=theC;
}
public double getSolution1()
{
}
public double getSolution2()
{
}
public String toString()
{
return a+"x^2 + "+b+"x + "+c+" =0";
}

}

• R.2.1.2 Complete the following function that computes the length of a line segment with end points (x1, y1) and (x2, y2). According to the Pythagorean theorem, the length is {$\sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}$}.

Lines.java

public class Lines
{
/**
Computes the length of a line segment
@param x1 the x-coordinate of the starting point
@param y1 the y-coordinate of the starting point
@param x2 the x-coordinate of the ending point
@param y2 the y-coordinate of the ending point
@return the length of the line segment joining (x1, y1) and (x2, y2)
*/
public static double segmentLength(double x1, double y1, double x2, double y2)
{

}
}


# LinesTester.java


public class LinesTester {

/**
* @param args
*/
public static void main(String[] args) {
System.out.print("Expecting 5:"+Lines.segmentLength(0,0,3,4));

}

}



• R2.1.3. DigitPeeler
1. Write a method that returns the last digit of an int
2. Write a method that returns the first digit of an int that has n digits.

# DigitPeeler.java

public class DigitPeeler {
/**
* DigitPeeler is a class that exists
* to make a small "library" of static functions,
* just in the same way that Math and Integer classes
* serve as a collection of static methods.
*
* You don't need to create an instance of this class
* to use these functions, because they are static
*/
public static int lastDigit(int n){

}
/**
* precondition: n has at least 1 digit
* @param n the number
* @param numberOfDigits of n
* @return the first digit of n
*/
public static int firstDigit(int n, int numberOfDigits){
//Hint: Math.pow(10,3) returns 1000

}
}



# DigitPeelerTester.java

public class DigitPeelerTester
{
public static void main(String[] args) {
System.out.println("This tests the DigitPeeler methods\n");
System.out.println("Last digit of 56834 is "+DigitPeeler.lastDigit(56834));
System.out.println("Expected 4\n");
System.out.println("First digit of 56834 is "+DigitPeeler.firstDigit(56834, 5));
System.out.println("Expected 5\n");
}
}

• R2.1.4 Write the following mathematical expressions in Java.
{$s=s_0+v_0t+\frac{1}{2}gt^2$}
{$G=4\pi^2\frac{a^3}{p^2(m_1+m_2)}$}
{$FV=PV\cdot\left(1+\frac{INT}{100}\right)^{YRS}$}
{$c=\sqrt{a^2+b^2-2ab\cos \theta}$}
• R2.1.5 Write the following Java expressions in mathematical notation.
a. dm = m * (Math.sqrt(1 + v / c) / (Math.sqrt(1 - v / c) - 1));
b. volume = Math.PI * r * r * h;
c. volume = 4 * Math.PI * Math.pow(r, 3) / 3;
d. p = Math.atan2(z, Math.sqrt(x * x + y * y));
• R21.6 What does Java report 4.35 * 100.0? Why?
• R2.1.7 Let n be an integer and x a floating-point number. Explain the difference between

n = (int) x; and n = (int) Math.round(x);

# 2.2: Conditional Statements and Loops

Use a truth table to show not(p and q) is equivalent to (not p) or (not q) (deMoivre Theorem)

 p q !p !q p && q !(p && q) !p || !q T T T F F T F F

Use a truth table to show not(p or q) is equivalent to (not p) and (not q) (deMoivre Theorem)

 p q !p !q p || q !(p || q) !p && !q T T T F F T F F

# Review Exercises

• R2.2.1 Find Errors in if Statements
a. if quarters > 0 then System.out.println(quarters + " quarters");
b. if (1 + x > Math.pow(x, Math.sqrt(2)) y = y + x;
c. if (x = 1) y ++; else if (x = 2) y = y + 2;
d. if (x && y == 0) { x = 1; y = 1; }
e. if (1 <= x <= 10) System.out.println(x);
f. if (! s.equals("nickels") || ! s.equals("pennies")|| !s.equals("dimes") || !s.equals("quarters"))System.out.print("Input error!");
g. if (input.equalsIgnoreCase("N") || "NO")return;
h. int x = Integer.parseInt(input) ;if (x ! = null) y = y + x;
i. language = "English";
if (country.equals("US"))
if (state.equals("PR")) language = "Spanish";
else if (country.equals("China"))
language = "Chinese";
• R2.2.2 Explain the difference between
s = 0;
if (x > 0) s ++;
if (y >	0) s ++;


and


s = 0;
if (x > 0) s ++;
else if (y > 0) s ++;

• R2.2.3 Use de Morgan's law to simplify the following Boolean expressions.
(a) ! (x > 0 && y > 0)
(b) !(x ! = 0 || y ! = 0)
(c) !(country.equals("US") && ! state.equals("HI") && !state.equals("AK"))
(d) ! (x % 4 ! = 0 | | ! (x % 100 == 0 && x % 400 == 0))
• R2.2.4 Explain the difference between the tests

r == s and r.equals(s) where both r and s are of type Rectangle. Click here for the Rectangle API

• R2.2.5 Explain why it is more difficult to compare floating-point numbers than integers. Write Java code to test whether an integer n equals 10 and whether a floating-point number x equals 10.

# 2.3: Strings

• R2.3.1Write a method that gets the last n characters from a string. For example, last("Hello, World!", 5) should return the string "orld!".
public class Strings
{
/**
Gets the last n characters from a string.
@param s a string
@param n a nonnegative integer <= s.length()
@return the string that contains the last n characters of s
*/
public String last(String s, int n)
{

}
}


# 2.4 The Integer and Double classes

• R2.4.1 If x is an int and s is a String, then which are true?
a. Integer.parseInt(“” + x) is the same as x
b. “” + Integer.parseInt(s) is the same as s
c. s.substring(0, s.length()) is the same as s

# 2.5 Arrays

Arrays and loops naturally go together. There is a nice review of Arrays and Loops at CodingBat.com Try the Array-1 Exercises at JavaBat

• R2.5.1 What does the following code print?
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
System.out.print(i * j % 10);
System.out.println();
}

• R2.5.2 How often do the following loops execute? Assume that i is an integer variable that is not changed in the loop body.
for (i = 1; i <= 10; i++) . . .

for (i = 0; i < 10; i++) . . .

for (i = 10; i > 0; i––) . . .

for (i = -10; i <= 10; i++) . . .

for (i = 10; i > = 0; i++) . . .

for (i = -10; i <= 10; i = i + 2) . . .

for (i = -10; i <= 10; i = i + 3) . . .

• R2.5.3 Rewrite the following for loop into a while loop.
  int s = 0;
for (int i = 1; i <= 10; i++) s = s + i;

• R2.5.4 What is an “off-by-one error”? Give an example from your own programming experience.
• R2.5.5 Which of the following varies the control variable from 100 to 1 in increments of -1?
a. for( int i = 100; i <= 1; i--)
b. for( int i = 100; i >= 1; i++)
c. for( int i = 100; i <= 1; i++)
d. for( int i = 100; i >= 1; i--)
• R2.5.6 What is the value of x after the following nested loop?

int x = 0;
for(int i = 0; i <= 5; i++)
for(int j = 0; j < i; j++)
x = x + j;

• R2.5.7 Mean and Standard deviation

The formula for the mean (or arithmetic mean or average) is {$\overline{x}=\frac{\sum x_i}{n}$} where {$\sum x_i = x_1 + x_2 + \dots + x_n$} for {$n$} scores

The formula for standard deviation is {$s=\sqrt{\frac{\sum x_i^2 - \frac{1}{n}\left( \sum x_i \right)^2}{n-1}}$}

You can compute this by keeping track of the count, the sum, and the sum of squares.

Here is a sample program run:

Enter Value, Q to quit: 5
Enter Value, Q to quit: 6
Enter Value, Q to quit: 8
Enter Value, Q to quit: 9
Enter Value, Q to quit: Q
There is a total of 4 values
The average is 7.0
The standard deviation is 1.8257418583505538


Here is some starter code for a dynamic tester:

import java.util.Scanner;
public class DynamicDataSetTester
{
public static void main(String[] args)
{
DataSet data = new DataSet();
Scanner kb=new Scanner(System.in);
String input="";
while( notDone(input) )
{
System.out.print("Enter an integer (Q to quit): ");
input = kb.nextLine();
if ( isAnInt(input) ){
}
}
System.out.println("DataSet data has "+data.getN()+" scores");

}
public static boolean notDone(String s){
boolean result=true;
if (s.length()>0 && s.substring(0,1).equalsIgnoreCase("Q") )
result=false;
return result;
}
public static boolean isAnInt(String s)
{
boolean result = true;
try {
Integer.parseInt(s);
} catch (NumberFormatException e){
result = false;
}
return result;
}
}



Here is a static tester program to use to test your DataSet class:

public class DataSetTester
{
public static void main(String[ ] args)
{
DataSet a = new DataSet();

System.out.println("count: " + a.getCount());
System.out.println("Expected: 4");
System.out.println("average: " + a.getAverage());
System.out.println("Expected: 7");
System.out.println(
"standard deviation: " + a.getStandardDeviation());
System.out.println("Expected: 1.83");
}
}

• R2.5.8 Write a program that contains a bounds error (Try to go past the size of an array). Run the program. What happens on your computer? How does the error message help you locate the error?
• R2.5.9. What is wrong with the following loop?
double[] data = new double;
for (int i = 1; i <= 10; i++ ) data[i] = i * i;


# 2.6: The List Interface and the ArrayList Class

Balloon Drop uses an ArrayList<Balloon>.

• R2.6.1 Write Java code for a loop that simultaneously computes the maximum and minimum values of an ArrayLlist.
• R2.6.2 Write a loop that reads 10 strings and inserts them into an array list. Write a second loop that prints out the strings in the opposite order from which they were entered.
• R2.6.3 Consider another variation of the algorithm for determining the maximum value. Here, we compute the maximum value of an array of numbers.
double max = 0; // Contains an error!
for (x : values)
{
if (x > max) max = x;
}


However, this approach contains a subtle error. What is the error, and how can you fix it?

• R2.6.4. For each of the following sets of values, write code that fills an array a with the values.

To help you get started, here is some "starter code" that will make an array a, fill it with 0's and print the contents of a

public class ArrayExperimenting
{
public static void main(String[] args) {
int [] a = new int;
for (int i=0; i<10; i++)
{
a[i]=0;
}
System.out.println("Contents of a:");
for (int element:a)
System.out.print(element + " ");
System.out.println();
}
}

import java.util.ArrayList;
public class ArrayListExperimenting
{
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=0; i<10; i++)
{
}
System.out.println("Contents of list:");
for (int element:list)
System.out.print(element+" ");
System.out.println();
}
}

(a)  1 2 3 4 5 6 7 8 9 10

(b)  0 2 4 6 8 10 12 14 16 18 20

(c)  1 4 9 16 25 36 49 64 81 100

(d)  0 0 0 0 0 0 0 0 0 0

(e)  1 4 9 16 9 7 4 9 11


Use a loop when appropriate.