P&CS Program #1: Hello World



P&CS Programming Labs

Lab #1: Programs 1-10 + Additional Exercises

For each of the programs below, follow these steps:

1. Run the sample program in JCreator (instructions below…)

2. Study the learning points for that sample program

3. At this point, if you have questions, ask for help.

4. Try the exercises to demonstrate your mastery of the learning points.

5. Save each of your exercises on your lab floppy disk

a. Do this using “File / Save As” in JCreator

b. If you are doing program 3, exercise 2, name the file “p3e2.java”

6. When you have mastered the exercises, inform the teacher and proceed to the next sample program.

How to create, compile, and run a sample program in JCreator:

1. Launch JCreator

2. Select “File / Close Workspace” if one is open.

3. Select “File / New / Files / Java File” ; Give it any name (say, “p1”)

4. Type in the Java program below, exactly as it appears!

a. Change and appropriately

5. Select “Build / Compile File” (do not use “Compile Project” nor F7!)

6. Look at the “Build” window at the bottom of the screen:

a. If there is an error, it will be reported here.

b. Wait to see the report. Do not go to Step 7 until you see the report.

c. If there is an error, hit F4 to go to the line number where the error occurred, then read the description of the error, try to fix it, and go back to Step 5.

d. If there is no error, wait for this screen to say “Process completed”. Then, and only then, proceed to Step 7.

7. Your program has now successfully compiled! (Congratulations!)

8. Select “Build / Execute File” (do not use “Execute Project” nor F5!)

P&CS Program #1: Hello World

// Program #1: Hello World

// , , p&cs

class HelloWorld

{

public static void main(String[] args)

{

System.out.println("Hello world!");

System.out.println("This is my first program!");

}

}

Learning Points:

1. A program is really a class with a main method.

2. The only part you really care about is the code inside the main.

a. The rest, you do not need to understand, but you do need to type in.

3. Java is very particular about the syntax.

a. Java is case-sensitive (you must get upper and lower case exactly correct)

b. Semicolons must follow statements

c. Your code can only go inside the main. Anywhere else is an error.

4. Good programmers (like you!) are very particular about style.

a. Use squiggly braces and indent your code exactly as noted above

b. Use comments to explain what the code does, who wrote it, etc.

c. Many more style rules to follow…

5. A line beginning with // is a comment, and Java ignores the line.

6. System.out.println(“foo”) prints the word “foo” followed by a newline.

Exercises:

1. Write a Java program which prints out your name.

2. Write a Java program which prints out a knock-knock joke.

P&CS Program #2: The Sum of Two Numbers

// Program #2: The Sum of Two Numbers

// , , p&cs

class SumOfTwoNumbers

{

public static void main(String[] args)

{

// declare two integer variables

int x, y;

// assign their values

x = 10;

y = 4;

// print out the variable values

System.out.println(x);

System.out.println(y);

// now print out their sum

System.out.println(x + y);

}

}

Learning Points:

1. Variables have names (like “x” and “y”) and hold values (like 10 and 4).

2. Integer variables have integer values

a. Some legal integer values: 2, 0, -20, 1234321

b. Some illegal values: 3.14, “hello”

3. You must declare variables before you use them.

a. This tells Java that these are variables, and what type (here, integers)

b. The line “int x, y;” declares the variables x and y to be integers

4. You can assign values to variables

a. “x = 10;” assigns the value 10 to the variable “x”

5. You can print out variables using System.out.println

6. You can even print out their sum using System.out.println

Exercises:

1. Write a Java program which prints out the product of two integers. Note that in Java, multiplication is performed with an asterisk (*).

2. Write a Java program which prints out the sum of three integers.

P&CS Program #3: Reading Integers

// Program #3: Reading Integers

// , , p&cs

class ReadingIntegers

{

public static void main(String[] args)

{

// declare two integer variables

int x, y;

// read their values from the user

x = readInt();

y = readInt();

// print out their sum

System.out.println(x);

System.out.println(y);

System.out.println(x + y);

}

}

Learning Points:

1. This is the same program as #2, except here the user enters the values

2. Thus, this program works for any values, and not just 10 and 4.

3. Unfortunately, as you learn when you enter this, it does not compile.

4. The problem is that Java does not know how to readInt().

5. To fix this, you must add the readInt() method, as on the following page.

6. You can download the readInt() code from the course home page.

7. You must include it if you use readInt() in your code.

Exercises:

1. Enter the whole Java program on the next page, including the readInt() method.

2. Write a Java program which reads in three integers and prints out their sum.

P&CS Program #3: Reading Integers (Full Listing)

// Program #3: Reading Integers

// , , p&cs

class ReadingIntegers

{

public static void main(String[] args)

{

// declare two integer variables

int x, y;

// read their values from the user

x = readInt();

y = readInt();

// print out their sum

System.out.println(x);

System.out.println(y);

System.out.println(x + y);

}

// Include this method if you use readInt() in your code.

// You may copy this code from the course web site.

public static int readInt()

{

int result, sign, c;

result = 0;

sign = 1;

try

{

// skip non-integer characters

while (true)

{

c = System.in.read();

if ((c >= '0') && (c '9'))

break;

}

}

catch (java.io.IOException e)

{

System.out.println("Error while reading integer.");

}

return result * sign;

}

}

P&CS Program #4: Reading Integers More Gracefully

// Program #4: Reading Integers More Gracefully

// , , p&cs

class ReadingIntegersMoreGracefully

{

public static void main(String[] args)

{

// declare two integer variables

int x, y;

// read their values from the user

System.out.print(“Enter an integer: “);

x = readInt();

System.out.print(“Enter another integer: “);

y = readInt();

// print out their sum

System.out.print(x);

System.out.print(“ + “);

System.out.print(y);

System.out.print(“ = “);

System.out.println(x + y);

}

// NOTE: insert readInt() code here...

}

Learning Points:

1. To run this program, you must include the readInt() code from program #3.

2. Here, we prompt the user (“Enter an integer: “), so the user knows what the program is asking.

3. Use System.out.print instead of System.out.println to stay on the same line.

4. We also print out the answer in a prettier format.

5. print(x) prints the value of the variable x

6. print(“foo”) prints whatever is inside the quotes.

7. All your Java programs for now on should use prompts and pretty output.

Exercises:

1. Write a Java program which reads in 3 integers and prints their sum and average.

2. Write a Java program which reads in a distance in yards and outputs the same distance in feet. Note that 1 yard = 3 feet.

3. Write a Java program which reads in a distance in feet and outputs the same distance in yards. Note what happens when the input is not a multiple of 3. This is known as truncation.

4. Write a program which reads in the number of free throws a player has attempted, and then the number she made, and prints out her free throw percentage. This is slightly trickier than the previous problems, due to truncation.

P&CS Program #5: If Statements

// Program #5: If Statements

// , , p&cs

class IfStatements

{

public static void main(String[] args)

{

// declare an integer variable

int x;

// read its value from the user

System.out.print(“Enter an integer: “);

x = readInt();

// use if statements to compare x to other values

if (x < 20)

{

System.out.println(x + “ is less than 20”);

}

if (x == 7)

{

System.out.println(x + “ is equal to 7”);

}

if (x != 19)

{

System.out.println(x + “ is not equal to 19”);

}

if (x > 3)

{

System.out.println(x + “ is greater than 3”);

}

}

// NOTE: insert readInt() code here...

}

Learning Points:

1. To run this program, you must include the readInt() code from program #3.

2. An “if” statement is of the form:

if (test)

{

BODY

}

3. An “if” statement executes its body only if its test is true

4. Important note: There is no semicolon after the test!!!

5. A test for equality uses double-equals, as in (x == y)

6. A test for inequality uses exclamation-equals, as in (x != y)

Exercises:

1. Write a Java program which reads in 2 integers and prints just the larger integer.

2. Write a Java program which reads in 2 integers and prints whether they sum to 0.

P&CS Program #6: If-Else Statements

// Program #6: If-Else Statements

// , , p&cs

class IfElseStatements

{

public static void main(String[] args)

{

// declare an integer variable

int x;

// read its value from the user

System.out.print("Enter an integer: ");

x = readInt();

// use if-else statements to find the sign of x

if (x < 0)

{

System.out.println(x + " is negative");

}

else if (x == 0)

{

System.out.println(x + " is equal to 0");

}

else

{

System.out.println(x + " is positive");

}

}

// NOTE: insert readInt() code here...

}

Learning Points:

1. To run this program, you must include the readInt() code from program #3.

2. Following an “if”, you may have an “else if” which provides another test

3. The last “else” can omit the test, in which case its body is executed only if all the preceding tests fail.

4. In any case, at most one body will be executed within in if-else statement. Think about this!

Exercises:

1. Write a Java program which reads in an integer, and if it is positive, prints out the square of the integer, but if it is negative, prints out the cube of the integer, and if it is zero, prints out the message “carpe diem”.

P&CS Program #7: While Statements

// Program #7: While Statements

// , , p&cs

class WhileStatements

{

public static void main(String[] args)

{

// This program uses a while statement to print out

// the numbers from 1 to 10, inclusive.

// declare the counter variable, which runs from 1 to 10

int counter;

// initialize the counter to 1

counter = 1;

// now, so long as the counter is ................
................

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

Google Online Preview   Download