Assignment1: Lab Etiquette

Variables, operations, and decisions

Your first Java lab

Practice storing values, calculating answers, and choosing what your program prints. Work through the ten problems in order; #10 is a challenge that combines the earlier skills.

  1. Create a file named Lab1.java using the starter below. Put your name, project, and date in the comment at the top.
  2. Write your code inside main, between the marked comments. Keep the class and method lines and their braces.
  3. For this lab, an input means a value you assign to a variable in your code. Change that value and run again to test. You do not need keyboard input, Scanner, loops, or additional methods.
  4. Print answers with System.out.println(...);. You do not need a return statement. Print a problem label before each answer so your output is easy to follow.
  5. Complete one problem at a time, then run the program. Use different variable names for different problems in main so declarations do not collide.
Quick reference

Java cheat sheet

1. Store a value in a variable

A variable has a type, a name, and a value: int count = 5;. The type tells Java what kind of value it can hold. End declarations and assignments with a semicolon.

The five types used in this lab
TypeStoresExample
intWhole numbers, including zero and negativesint count = 5;
doubleNumbers that can have a fractional part; decimal results may be approximatedouble price = 2.50;
charOne character, in single quoteschar initial = 'J';
StringText, in double quotes; use a capital SString name = "Jordan";
booleantrue or false, without quotesboolean ready = true;

Java is case-sensitive: score and Score are different names. Declare a variable once in the same block; leave off its type when changing its value.

int count = 5;                 // Declare and initialize.
count = 8;                     // Replace the old value.
count = count + 1;             // Read the old value, then store 9.
System.out.println("Count: " + count); // Prints Count: 9

= stores the value on its right in the variable on its left. Copying a number into another variable does not keep the two variables linked.

2. Calculate and print

Arithmetic and text operations
OperationMeaningExample result
+Add numbers7 + 2 is 9
-Subtract7 - 2 is 5
*Multiply7 * 2 is 14
/Divide; two integers give an integer result, discarding the fractional part7 / 2 is 3; 7 / 2.0 is 3.5
%Find the remainder after division7 % 2 is 1; 8 % 2 is 0
+ with textJoin text and values"Score: " + 8 is "Score: 8"

Use parentheses to group calculations: (6 + 4) / 2.0 is 5.0. Multiplication, division, and remainder happen before addition and subtraction. Do not divide by zero.

System.out.println("Hello!");          // Print text, then start a new line.
System.out.println("Total: " + (4 + 2)); // Prints Total: 6

Common trap: double result = 7 / 2; stores 3.0, because integer division happens first. Use 7 / 2.0 to keep the fraction. To square a number, multiply it by itself; ^ is not Java's exponent operator.

3. Compare values

A comparison produces a boolean result: true or false.

Comparisons and boolean operations
OperatorMeaningExample
== / !=Equal / not equal (numbers, characters, booleans)5 == 5 is true
< / <=Less than / less than or equal5 < 5 is false
> / >=Greater than / greater than or equal5 >= 5 is true
&&AND: both conditions must be true(5 > 0) && (5 < 10) is true
||OR: at least one condition must be true(5 < 0) || (5 == 5) is true
!NOT: reverse a boolean!true is false
.equals(...)Compare String contents; capitalization matters"rock".equals("paper") is false

Remember: = assigns; == compares. Use choice.equals("rock") to compare text, rather than choice == "rock".

4. Make a decision with if

An if runs its block only when the condition in parentheses is true. An else runs when that condition is false. Put the statements for each branch inside braces.

boolean ready = true;
if (ready) {
    System.out.println("Let's begin!");
} else {
    System.out.println("Take a moment to get ready.");
}

For more than two possibilities, use else if. Java checks this chain from top to bottom and runs only the first matching branch, or the final else if none match.

int books = 2;
if (books == 0) {
    System.out.println("No books yet.");
} else if (books == 1) {
    System.out.println("One book.");
} else {
    System.out.println("More than one book.");
}

An else is optional when nothing needs to happen for a false condition. Do not put a semicolon immediately after if (...).

Starter code

Copy this into Lab1.java. The file name must match public class Lab1. Replace each TODO comment with your work; add as many lines as you need.

/*
 * Name:
 * Project: Assignment1: Lab Etiquette
 * Date:
 */
public class Lab1 {
    public static void main(String[] args) {
        // START: Write your lab code below this line.

        System.out.println("Problem 1");
        // TODO: Greeting and student information

        System.out.println("Problem 2");
        // TODO: Guided swap

        System.out.println("Problem 3");
        // TODO: Square a number

        System.out.println("Problem 4");
        // TODO: Find the larger number

        System.out.println("Problem 5");
        // TODO: Put the larger value first

        System.out.println("Problem 6");
        // TODO: Check for a negative number

        System.out.println("Problem 7");
        // TODO: Even or odd

        System.out.println("Problem 8");
        // TODO: Average and letter grade

        System.out.println("Problem 9");
        // TODO: Boolean message

        System.out.println("Problem 10");
        // TODO: Rock, paper, scissors challenge

        // END: Keep the two closing braces below.
    }
}

The 10 problems

Use the starting values first, then try the checks. Your answers must come from the variables and calculations, not from typing the expected answers directly into print statements.

1. Say hello

Print Hello world!!!. Then declare String studentName = "Jordan"; and char section = 'A';. Use those variables to print the second line below.

Hello world!!!
Student: Jordan, section: A

Check: Change the name and section to your own. Both should change in the output. Use + to join text and values.

2. Swap two values, step by step

Declare int a = 10; and int b = 20;. A swap means that a ends with the original value of b, and b ends with the original value of a.

Why a third variable? If you write a = b; first, the original value in a is overwritten. Writing b = a; afterward would copy 20 again. A temporary variable holds the original value so it is not lost.

  1. Print the starting values as shown below.
  2. Create the temporary storage with int temp = a;. Now temp holds a copy of 10.
  3. Write an assignment that copies the value of b into a.
  4. Write an assignment that copies the saved value in temp into b.
  5. Print both variables again. Do not swap by typing a = 20; and b = 10;; the same code should work for other starting numbers.
Before: a = 10, b = 20
After: a = 20, b = 10

Check: With starting values a = -3 and b = 7, the final values should be a = 7 and b = -3. Trace the values of a, b, and temp on paper after each assignment.

3. Square a number

Declare int numberToSquare = 3;. Multiply the variable by itself, store the result in an int named squared, and print the result.

Square: 9

Check: Try -4 (expect 16) and 0 (expect 0). Use * for multiplication.

4. Find the larger number

Declare int firstNumber = 4; and int secondNumber = -5;. Use if, else if, and else to print the larger value. If the values are equal, print The numbers are equal. Leave both variables unchanged.

Larger: 4

Check: Try 2, 9 (print Larger: 9) and 6, 6 (print the equality message). Check whether the first number is greater, then whether the second is greater.

5. Put the larger value first

Declare int firstValue = 10; and int secondValue = 21;. If firstValue is less than secondValue, swap their values using the temporary-variable technique from #2. Otherwise, leave them alone. Print both values after the if, so they print whether or not a swap happens.

firstValue = 21, secondValue = 10

Hint: The three swap statements belong inside the if braces. Use a new temporary-variable name, such as savedValue.

Check: Starting values 30, 5 should stay 30, 5; 8, 8 should stay 8, 8.

6. Is the number negative?

Declare int numberToCheck = -6;. Use an if / else to print Negative when the value is less than zero, or Not negative otherwise.

Negative

Check: Both 4 and 0 should print Not negative. Zero is not negative; it is not positive either.

7. Even or odd?

Declare int wholeNumber = 8;. Print Even if it divides by 2 with no remainder; otherwise print Odd. Use % to find the remainder and compare it with zero.

Even

Check: 7 is odd, 0 is even, -4 is even, and -3 is odd. Checking for remainder zero works for negative numbers too.

8. Calculate an average, then a letter grade

Declare three double variables with these starting values: gradeOne = 94.0, gradeTwo = 87.0, and gradeThree = 75.0. Assume each grade is between 0 and 100, inclusive.

  1. Add all three grades in parentheses and divide their sum by 3.0. Store the answer in double average and print it.
  2. Use an if / else if / else chain to print a letter grade using the table below. Check the highest cutoff first.
Grading scale for this exercise
AverageLetter
90 through 100A
At least 80 but less than 90B
At least 70 but less than 80C
At least 60 but less than 70D
Less than 60F
Average: 85.33333333333333
Letter grade: B

No rounding or special decimal formatting is required. Choose the letter from the unrounded average: 89.9 is a B.

Check: Set all three grades to 90.0 (A), then 80.0 (B), 70.0 (C), 60.0 (D), and 59.0 (F). Also check all zeros (F) and all hundreds (A).

9. Let a boolean choose the message

Declare boolean isReady = true;. Use if (isReady) and else to print Ready to begin! when it is true, or Not ready yet. when it is false.

Ready to begin!

Check: Change only the starting value to false and run again. You should see only Not ready yet. A boolean can be used directly as the condition; it does not need quotes or a comparison with true.

Challenge

10. Rock, paper, scissors

Declare String playerOne = "rock"; and String playerTwo = "paper";. Each value will be exactly "rock", "paper", or "scissors", all lowercase. Simulate one round; no keyboard input, random choices, or invalid-input handling is required.

Rules: Rock beats scissors, scissors beats paper, and paper beats rock. Matching choices are a tie. Print exactly one result: Player 1 wins!, Player 2 wins!, or Tie!.

  1. Check for a tie first with playerOne.equals(playerTwo).
  2. Next, check the three ways Player 1 can win. For one winning pair, both choices must match: playerOne.equals("rock") && playerTwo.equals("scissors"). Add the other two winning pairs with separate else if branches, or join the pairs with ||.
  3. If it is not a tie and none of Player 1's winning pairs match, Player 2 wins.
Player 2 wins!
Test all nine pairs; each cell is the expected result
Player 1 choicePlayer 2: rockPlayer 2: paperPlayer 2: scissors
rockTie!Player 2 wins!Player 1 wins!
paperPlayer 1 wins!Tie!Player 2 wins!
scissorsPlayer 2 wins!Player 1 wins!Tie!

Before submitting

Submit your completed Lab1.java file to [email protected].

Back to assignments