Program Template



Examples

1.Program Template

//comments identifying yourself

//comments describing what the program does and how it is used (e.g. what input is

// required)

import java.io.*;

.

.

.

class PutYourClassNameHere

{

public static void main(String xxx[])

{

//declarations of variables and data

// code to read initial values

// code for the algorithm’s body

// code to print out final values

}

//definitions for the methods used by main go here

}

2. class PutYourClassNameHere

{

public static void main(String xxx[]) throws IOException

{

//declarations of variables and data

//code to read initial values

//code for the algorithm’s body

//code to print out final values

}

//definitions for the methods used by main go here

}

Class Specification

//comments identifying yourself

// This file define a class of Car, which has three methods to simulate the behavior of car

class Car

{

private double speed;

private boolean engineOn;

public Car() //constructor

{

this.speed = 0.0;

this.engineOn = false;

}

public void turnEngineOn()

{

this.engineOn = true;

}

public void accelerate()

{

this.speed += 10.0;

// or this.speed = this.speed + 10.0;

}

public double getCurrentSpeed()

{

return this.speed;

}

}

3.

Algorithm 1

//comments identifying yourself

// This file define a class calculator to calculate the sum and average of three number.

class Calculator

{

private double A;

private double B;

private double C;

public Calculator (double Number1, double Number2, double Number3)

{

A = Number1;

B = Number2;

B = Number3;

}

public double getSum()

{

double sum;

sum = A + B + C;

return sum;

}

public double getAvg()

{

double sum;

double avg;

sum = this.getSum();

avg = sum/3;

return avg;

}

}

4. MaxVariablesDemo

// Display the maximum value of data type

public class MaxVariablesDemo

{

public static void main(String args[])

{

// integers

byte largestByte = Byte.MAX_VALUE;

short largestShort = Short.MAX_VALUE;

int largestInteger = Integer.MAX_VALUE;

long largestLong = Long.MAX_VALUE;

// real numbers

float largestFloat = Float.MAX_VALUE;

double largestDouble = Double.MAX_VALUE;

// other primitive types

char aChar = 'S';

boolean aBoolean = true;

// display them all

System.out.println("The largest byte value is " + largestByte);

System.out.println("The largest short value is " + largestShort);

System.out.println("The largest integer value is " + largestInteger);

System.out.println("The largest long value is " + largestLong);

System.out.println("The largest float value is " + largestFloat);

System.out.println("The largest double value is " + largestDouble);

if (Character.isUpperCase(aChar))

{

System.out.println("The character " + aChar + " is upper case.");

}

else

{

System.out.println("The character " + aChar + " is lower case.");

}

System.out.println("The value of aBoolean is " + aBoolean);

}

}

1. Modify the program so that aBoolean has a different value

2. Rewrite the program to display the minimum value of each integer data type.

3. Modify the program to determine the capitalization of a character (isUpperCase?)

5. Reading Input

//Show how to read a double the hard way

import java.io.*;

import java.text.*;

public class ReadDoubleTest

{

public static void main(String[] args)

{

double x;

System.out.println("Enter a number, I will add two to it.");

try

{

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

String s = br.readLine();

DecimalFormat df = new DecimalFormat();

Number n = df.parse(s);

x = n.doubleValue();

}

catch (IOException e)

{

x = 0;

}

catch (ParseException e)

{

x = 0;

}

System.out.println( x + 2);

}

}

Solution for Exercise

1.FloatTest.java

public class FloatTest

{

public static void main(String[] args)

{

float f = 100.0f;

float MAX = 0.001f;

float MIN = -MAX;

System.out.print(String.valueOf(f));

if ((f < MAX) && (f > MIN))

{

System.out.println(" is pretty darn close to 0.");

}

else

{

System.out.println(" is not close to 0.");

}

}

}

2. CurrencyExchage.java

//DecimalFormat is discussed in

//

import java.text.DecimalFormat;

public class CurrencyExchange

{

static double FRANCS_PER_DOLLAR = 6.85062;

public static void main(String[] args)

{

DecimalFormat formatter = new DecimalFormat("###,###.00");

double numFrancs = 10000000.0;

double numDollars = numFrancs/FRANCS_PER_DOLLAR;

System.out.println(formatter.format(numFrancs) + "FF is equal to $"

+ formatter.format(numDollars) + ".");

}

}

3. Bits.java

public class Bits

{

//Note: It's acceptable to use int instead of short throughout this program.

static final short READY = 1;

static final short PROCESSING = 2;

static final short RECOVERING = 4;

static final short ERROR = 8;

static final String READY_STRING = "ready to receive requests";

static final String PROCESSING_STRING = "processing a request";

static final String RECOVERING_STRING = "error recovery in progress";

static final String ERROR_STRING = "unrecoverable error occurred";

public static void main(String[] args)

{

short status = 7;

if ((status & READY) == READY)

{

System.out.println(READY_STRING);

}

if ((status & PROCESSING) == PROCESSING)

{

System.out.println(PROCESSING_STRING);

}

if ((status & RECOVERING) == RECOVERING)

{

System.out.println(RECOVERING_STRING);

}

if ((status & ERROR) == ERROR)

{

System.out.println(ERROR_STRING);

}

}

}

What is the output when status is 8?

Solution: unrecoverable error occurred

What is the output when status is 7?

Solution: ready to receive requests, processing a request, error recovery in progress

4.

Exercise: What output do you think the code will produce if aNumber is 3?

Solution:

second string

third string

Exercise: Write a test program containing the code snippet; make aNumber 3. What is the output of the program? Is it what you predicted? Explain why the output is what it is. In other words, what is the control flow for the code snippet?

Solution:

second string

third string

public class NestedIf

{

public static void main(String[] args)

{

int aNumber = 3;

if (aNumber >= 0)

if (aNumber == 0) System.out.println("first string");

else

System.out.println("second string");

System.out.println("third string");

}

}

3 is greater than or equal to 0, so execution progresses to the second if statement. The second if statement's test fails because 3 is not equal to 0. Thus, the else clause executes (since it's attached to the second if statement). Thus, second string is displayed. The final println is completely outside of any if statement, so it always gets executed, and thus third string is always displayed.

Exercise: Using only spaces and line breaks, reformat the code snippet to make the control flow easier to understand.

Solution:

if (aNumber >= 0)

if (aNumber == 0)

System.out.println("first string");

else

System.out.println("second string");

System.out.println("third string");

Exercise: Use braces { and } to further clarify the code and reduce the possibility of errors by future maintainers of the code.

Solution: Adhering to the Sun code conventions:

if (aNumber >= 0)

{

if (aNumber == 0)

{

System.out.println("first string");

}

else

{

System.out.println("second string");

}

}

System.out.println("third string");

Variables

Which of the following are valid variable names?

1. int n

2. anInt y

3. I y

4. i1 y

5. 1 n

6. thing1 y

7. 1thing n

8. ONE-HUNDRED n

9. ONE_HUNDRED y

10. something2do y

Operators

1. Consider the following code snippet:

int i = 10;

int n = i++%5;

Question: What are the values of i and n after the code is executed?

Answer: i is 11, and n is 0.

Question: What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))?

Answer: i is 11, and n is 1.

2. Question: What is the value of i after the following code snippet executes?

int i = 8;

i >>=2;

Answer: i is 2.

3. Question: What is the value of i after the following code snippet executes?

int i = 17;

i >>=1;

Answer: i is 8.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download