0% found this document useful (0 votes)
34 views

Revised Potato Pirates x Java (3-Hour Resource)

Uploaded by

Gorka Diaz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Revised Potato Pirates x Java (3-Hour Resource)

Uploaded by

Gorka Diaz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

CONTACT

Website: www.potatopirates.game
Email: [email protected], [email protected]

Copyright © 2022 by Codomo Pte Ltd

All rights reserved. No part of this document may be reproduced, distributed, or


transmitted in any form or by any means, including photocopying, recording, or other
electronic or mechanical methods.
Ahoy Mateys! Welcome aboard
Potato Pirates X Java!

Embark on a journey to discover Java


with the help of our Potato Pirate cards
and friendly Tater crew! Now make
haste- Anchors Aweigh!
Contents

1. Getting Started
a. What is Java? 3
b. What is a programming language? 3
c. Downloading & installing Eclipse 4
d. My first Java program 5

2. Chapter 1: Variables
a. What are variables? 8
b. Get the value of a variable 9
c. Comments 9
d. Updating the value of a variable 10
e. Why do we use variables? 10
f. Mathematical operators 11
g. Strings 12
h. String concatenation 13
i. String indexing 14
j. Data types 15
k. Type casting 15
l. Exercise 16

© Copyright Codomo Pte Ltd 2022 1


Contents

3. Chapter 2: For-Loop
a. What is a for loop? 18
b. Breakdown (for loop) 19
c. Nested for loop 20
d. Breakdown (nested for loop) 21
e. Exercise 22

4. Chapter 3: While Loop


a. What is a while loop? 24
b. Breakdown (while loop) 25
c. Comparison operators 26
d. Logical operators 26
e. Comparisons & logical operators in Java 27
f. Exercise 28

5. Chapter 4: If-Else & Switch statement


a. What is an if-else statement? 31
b. Breakdown (if statement) 32
c. What is a switch statement? 33
d. Breakdown (switch statement) 34
e. Exercise 35

6. Java Syntax Cheat Sheet 37

7. Answer Sheet 38

© Copyright Codomo Pte Ltd 2022 2


Getting Started
What is Java?
Java is a computer programming language that can be used for a
wide array of applications. Popular games like Minecraft were
programmed with Java. It’s also used for android development,
server management, SIM cards, security systems, blu-ray
technology… Java is all around you!

Making games Android Development Server management

Err.. what’s a programming language?


Just like humans communicate with one another using many
different languages, computers use programming languages to
communicate with other computers. Java is one of the languages
commonly used to do so.

Human language Computer language

© Copyright Codomo Pte Ltd 2022 3


Getting Started
Download

1. Go to https://www.eclipse.org/downloads/
2. Download Eclipse Installer (32 or 64 bit).

Install

1. Double click on Eclipse Installer.


2. Select Eclipse IDE for Java Developers.
3. You may customise or accept the default installation folder. If
unsure, just accept the default settings.
4. Accept License agreement.
5. Installation should begin. Please wait for a few minutes.
6. Voila! You are now ready to program some Java code.

Do note that “Eclipse ID 2021-12” is the version name at the time


of writing. The name may differ overtime due to software updates.

Opening Eclipse

Below are the shortcuts to find Eclipse.

Windows
1. Go to Start button.
2. Type “Eclipse” in the “Search programs and files textbox”.

Macintosh OS
1. Press Cmd + space
2. Type “Eclipse”

© Copyright Codomo Pte Ltd 2022 4


Getting Started
My first Java Program
We’re going to write our very first Java program that will display
“Ahoy Matey” when run. Ready? Let’s go!

After you have opened Eclipse,


1. You may customise or accept the default workspace folder.
2. Click ‘Launch’ under default conditions when the pop-up
appears.
3. After startup, close the welcome page.

Closing the welcome page

© Copyright Codomo Pte Ltd 2022 5


Getting Started
To create a Java Project,
1. Click ‘File’ → ‘New’ → ‘Java Project’.
2. Name the project and click ‘Next’, then ‘Finish’.
Click “Don’t Create” when asked to create a new module.
3. Click ‘New Java Class’.
4. Choose a name and click (in our case, we use the name
“HelloWorld”).
5. Check the box named ‘public static void main (String [] args)’
and click ‘Finish’.

1. 2.

3. 4.

5.

© Copyright Codomo Pte Ltd 2022 6


Getting Started
Let’s write our first code.
1. Type System.out.println(“Ahoy, Matey!”); below the
line
// TODO Auto-generated method stub
2. Click ‘run’.
3. Save HelloWorld.java if prompted.
4. A message “Ahoy Matey!” will appear at the console. The
console is located below your Eclipse window.
1. 2.

3.

What’s happening?
When you write System.out.println(“Ahoy, Matey!”);
, you are telling the system to print out the line “Ahoy, Matey!”.
Try changing “Ahoy, Matey!” to other texts. See what happens.

© Copyright Codomo Pte Ltd 2022 7


Variables
What are variables?
A variable acts like a container that stores data. For example, we
can use a variable to represent the number of crew members in a
ship. Below is a ship with 10 potatoes. Create a variable called
“crew” by typing int crew = 10; “crew” is the variable name,
and 10 is the value that it stores. More examples ahead.

In Potato Pirates In Java

int crew = 10;

In Java, we need 3 components to initialise a variable.


Data Type
‘int’ stands for integer (whole numbers), Value
which is the data type of this variable. The value stored in this
More on data types later. variable is 10.

int crew = 10;

Variable name
Every variable is identified with a name. This name can be anything you
want as long as it’s not a keyword.
More on keywords in the cheat sheet!
© Copyright Codomo Pte Ltd 2022 8
Variables
Getting the value of a variable
After storing a value in a variable we can retrieve it by “calling” its
name. The code below demonstrates how to retrieve a value stored
in a variable.

Java Code:
public static void main(String[] args) {
int crew = 10; // Set variable “crew” as 10
System.out.println(crew); // print the value of “crew”
}

Psst.. // is a symbol for


comments in Java.

Console:

Comments ( // symbol )
A comment is a programmer-readable explanation which is usually
used to explain the meaning of certain lines of code. Words
appearing after // will be ignored by the computer. Very useful!

© Copyright Codomo Pte Ltd 2022 9


Variables
Updating the value of a variable
You get a Potato King card, and receive 2 extra potatoes. How do
we increase the value of crew by 2? See below.

public static void main(String[] args) {


int crew = 10; // Set variable “crew” as 10
crew = crew + 2; // Increase “crew” by 2
System.out.println(crew); // print “crew”
}

Why do we use variables?


Data is constantly changing. To handle all these changes, values
need to be stored in a variable, which can then be modified. For
example, the number of potatoes on a ship changes as the game
progresses. We use variables to keep track of all these numbers.

10 crew 6 crew 3 crew

You may start with 10... ..and end up with 3!

© Copyright Codomo Pte Ltd 2022 10


Variables
Mathematical Operators
When writing code, the BODMAS order of operations still applies.
If you’ve forgotten your BODMAS rules this could help jog your
memory:

Brackets: ( ) Division: / Addition: +

BODMAS
Order: ** Multiplication: * Subtraction: -

Note: There is also the modulo (or remainder) operator: %. It


returns the remainder when the number to its left is divided by the
number to its right. E.g.
10%2 = 0
5%2 = 1
20%3 = 2

Can you guess the answer? 4) 7


3) 3
1) (2+2)-1 My Prediction: Java Returns __ 2) 21
2) (14*9)/6 My Prediction: Java Returns __ 1) 3
3) 17%(3+4) My Prediction: Java Returns __ Answer
4) 49/(17%10) My Prediction: Java Returns __

Try your best to answer these


questions without coding them!

© Copyright Codomo Pte Ltd 2022


11
Variables
Strings
Strings are used to store and manipulate a string of characters. Any
series of characters enclosed by quotation marks (“ “ or ‘ ‘) represent
a string. Strings are very useful for displaying text on your screen.

Oh, and don’t forget to use String as your data type when
initialising it! Try running the code below on Eclipse:

Java Code:
public static void main(String[] args) {
String control1 = "for 3 times, ";
String action1 = "roast";

System.out.println(control1);
System.out.println(action1);
}

Console:

© Copyright Codomo Pte Ltd 2022


12
Variables
String concatenation
Concatenation means to join strings together. To join strings
together, we use the ‘+’ operator. See the fourth line.

Java Code:
public static void main(String[] args) {
String control1 = "for 3 times, ";
String action1 = "roast";
String final_words = control1 + action1;

System.out.println(final_words);
}

Console:

© Copyright Codomo Pte Ltd 2022


13
Variables
String indexing
Let’s say we have a variable named “bar” storing the string
“POTATO” and we want to get the letter ‘A’ from the string. We
first need to figure out the index (ie. position) of ‘A’. If you think
the index is 4, you’re on the right track, but there’s a small catch…
The index is 3, not 4.

String bar = “POTATO”;


0 1 2 3 4 5

Let’s extract the letter ‘A’. Below is the Java code to extract it.

Java Code:
public static void main(String[] args) {
String bar = "POTATO";
char foo = bar.charAt(3);
System.out.println(foo);
}
‘char’ refers to ‘character’ data type
Returns the character at index 3

Console:

© Copyright Codomo Pte Ltd 2022


14
Variables
Data types
There are many different data types in programming like integers,
strings, floats, booleans, arrays, tuples, bytes and many more.
We’ll only be focusing on these for this learning resource.
Data Type Integer String Character Boolean

Expression int String char boolean

Type casting
Java includes methods to convert from one data type to another.
Run the code below to convert between string & integers.
Converting Integer to String
public static void main(String[] args) {
int x = 3;
String x_str = Integer.toString(x);
System.out.println(x_str+"potatoes");
}
Convert x to string
Concatenate 2 strings

Converting String to Integer


public static void main(String[] args) {
String y = "3";
int y_int = Integer.valueOf(y);

System.out.println(y_int+2); Convert y to integer


}
Add y with 2

Why is Type Casting important?


Type System.out.println(y+2); below System.out.println(y_int+2);
Run both lines of code and compare the results. Even though both y_int and y
represents 3, do they show the same result when 2 was added? No, and the reason for
that is because when a digit is type casted as a string, Java sees it as a word rather than a
number, hence y+2 combines them rather than adds them mathematically. Therefore,
ensure that your variables are set to the correct data type to avoid errors like above.
© Copyright Codomo Pte Ltd 2022
15
Variables (Exercise)
Getting & Updating Variable

1. Initialise a variable “x” with value 10. Then, add 5 to it. The
final value of x should print 15.
2. Initialise a variable “a” with value 10. Then, divide it by 2. The
final value of “a” should print 5.
3. Initialise a variable “b” with value 12. Then, divide it by 3.
Find the remainder.

Mathematical Operators (Predict the answer without your computer!)

public static void main(String[] args) {


int k = 20 + 10 * 20 -20;
System.out.println(k);
} k = ___

public static void main(String[] args) {


int z = 100 % 49;
System.out.println(z);
} z = ___

public static void main(String[] args) {


int x = 5;
x = x + 1;
System.out.println(x);
int y = x + 10;
y = 2*x + 1;
System.out.println(y);
x = ___
} y = ___

© Copyright Codomo Pte Ltd 2022


16
Variables (Exercise)
String Concatenation & Indexing

1) String a = “Hello, ”, String b = “Potato King”. Concatenate


both strings and print out “Hello, Potato King”.

2) String word1 = “POTATO PIRATES”. Get the letter ‘S’ from


word1.

Data Types

1) String x = “10”. Convert x to an integer, and add 20 to it. You


should get 30.
2) int y = 7. Convert y into a String and print “7 Potato Kings”.

© Copyright Codomo Pte Ltd 2022


17
For Loop
What is a for loop?
Suppose you wanted to print the word “Mash” 1000 times. How
do you do it? You can write the println statement 1000 times but
that would be a little silly. Thankfully, for loops are here to help!
For loops make repetitive tasks very easy to perform. Let’s see how
they are used in Java.

In Potato Pirates In Java

for (int i=1;i<=3;i++) {


System.out.println("Mash");
}

Type this out in the Eclipse IDE and see what it does.
When you’re done, let’s take a closer look at each part of the code.

© Copyright Codomo Pte Ltd 2022


18
For Loop
Breakdown (for loop)
Let’s take a closer look at the structure of a for loop.

initialisation condition increment

for (int i=1;i<=3;i++)


Legend
Initialisation: The initial value of i in the first iteration of the loop!
Condition: Loop will execute the action until condition is false
Increment: Change in the value of i from one iteration to the next
The letter “i” is a ‘dummy variable’. It is a temporary variable that exists within the loop.

Below shows the process of how a for loop will work. On the first
iteration, the variable “i” will carry the value of 1. On the next
iteration, it will increase by 1. The loop continues until the
condition is no longer met and becomes false.

Iteration Value of i
Did you know?
st
1 1 In Java, i = i + 1 can
be written as i++
2nd 2

3rd 3

Loop terminates as the variable


i cannot be greater than 3.

© Copyright Codomo Pte Ltd 2022


19
For Loop
Nested for loop
In the Potato Pirates game, we can stack several for loop cards on
top of each other to repeatedly execute attacks (Fry, Mash etc.)
You can do the same in Java as well by placing for loops within
other for loops, or in programming terms, nesting them.

Nested/
In Potato Pirates Outer loop In Java Inner loop

for (int j=0;j<3;j++) {


for (int i=0;i<3;i++) {
System.out.println("Fry");
}
}

Loop-ception.
What a beauty!

© Copyright Codomo Pte Ltd 2022


20
For Loop
Breakdown (nested for loop)
The Eclipse IDE reads and executes code line by line. Since the
outer loop encompasses the inner loop, it executes the inner loop 3
times. Every execution of the inner loop then prints “Fry” on the
screen 3 times. How many times will “Fry” be printed out in total?
Give it a try.

Outer Loop
for (int j=0;j<3;j++) {
for (int i=0;i<3;i++) {
System.out.println("Fry");
}
}

Inner Loop
for (int j=0;j<3;j++) {
for (int i=0;i<3;i++) {
System.out.println("Fry");
}
}

© Copyright Codomo Pte Ltd 2022


21
For Loop (Exercise)
Basic Questions

1) Generate the following number sequence: 1,2,3,...,100.


2) Generate the following number sequence: 3,4,..,20.

Convert Potato Pirates to Java

1) An enemy ship has 10 potato crew


members. It is attacked by the cards on
the left. Show that there are 8 potato
crew members left.

2) The variable y represents the number of


ships you have. You have 2 ships, and
the enemy has 30 potato crew members.
Show that there are 12 potato crew
members left.

© Copyright Codomo Pte Ltd 2022


22
For Loop (Exercise)
Convert Potato Pirates to Java

3) An enemy ship has 10 potato crew


members. It was attacked by the card on
the left, and it has 4 potatoes left. How
many cards does the enemy have?

4) Fill in the blank such that the code


below will perform the code shown on
the cards.

Code:
for (int i=5; i<____; i+=5){
enemy_crew = enemy_crew - 1;
}

© Copyright Codomo Pte Ltd 2022


23
While Loop
What is a while loop?
Just like for loops, a while loop also repeats based on a condition;
albeit with a slight difference. The loop will repeatedly execute its
action until the stated condition becomes false. Let’s find out how
they are used.

In Potato Pirates In Java

while (crew > 4) {


System.out.println("Mash");
}

Type this out in the Eclipse IDE and see what it does. Remember
to declare the variable “crew” before this code. When you’re done,
let’s take a closer look at each part of the control statement.

Note: Hit the red button above the output to stop the infinite loop!

© Copyright Codomo Pte Ltd 2022


24
While Loop
Breakdown (while loop)
Let’s take a closer look at the structure of a while loop.
condition

while (crew > 4)


A boolean expression is one which can either take a True or False value. The
condition check of “crew > 4” returns a boolean value. The while loop will stop
running when the value returned by the condition check is false.

The example below shows how a while loop will work. The crew
begins with 7 crew members. On the first iteration, the while loop
will check if there are more than 4 crew members. Since 7 > 4 is
true, it will execute the action to reduce the crew by 2. On the
next iteration, the action will run again as 5 > 4. Finally, it stops at
the third iteration as 3 > 4 is false.

int crew = 7;
while (crew > 4) {
crew = crew - 2;
}
System.out.println(crew);

Iteration Value of crew Is crew > 4? Action

1st 7 TRUE Reduce crew by 2

2nd 5 TRUE Reduce crew by 2

3rd 3 FALSE NA

© Copyright Codomo Pte Ltd 2022


25
While Loop
Comparison Operators
Comparison operators are used to compare 2 objects, and will
either return ‘true’ or ‘false’ (also known as booleans).

Comparison Operators Quick Examples


Equal to == Expression Output

Not equal != 1 == 1 TRUE

Less than < 1 != 1 FALSE

Greater than > 3<4 TRUE

Less than or equal <= 1 > 10 FALSE


to
5 <= 5 TRUE
Greater than or >=
equal to 8 >= 10 FALSE

Logical Operators
Logical operators are typically used with boolean values. When
they are, they return a boolean value. Below are some examples.

Logical Operators Quick Examples


AND && A B A && B A || B

OR || TRUE TRUE TRUE TRUE

NOT ! TRUE FALSE FALSE TRUE

FALSE TRUE FALSE TRUE

FALSE FALSE FALSE FALSE

© Copyright Codomo Pte Ltd 2022


26
While Loop
Comparison and logical operators in Java
Below are some examples of how comparison and logical operators
are used in Java.

Java Code:
public static void main(String[] args) {
int crew1 = 3;
int crew2 = 5;
boolean isDead = false;
System.out.println(crew1 == 3);
System.out.println(crew2 <= 2);
System.out.println(crew1 > crew2);
System.out.println(crew1>crew2 && crew2 ==5);
System.out.println(crew1>crew2 || crew2 ==5);
System.out.println(!isDead);
}

Console:

© Copyright Codomo Pte Ltd 2022


27
While Loop (Exercise)
Basic Questions

1) Generate this sequence of number with while loop: 10,9,...,1.


2) Generate this sequence of number with while loop: 10,9,..,5.

Predict the result (Do this without your computer!)


int crew = 20;
while (crew >= 8) {
crew = crew - 1;
}
System.out.println(crew);
crew = ___

int crew = 20;


while (crew == 10) {
crew = crew - 1;
}
System.out.println(crew);
crew = ___

© Copyright Codomo Pte Ltd 2022


28
While Loop (Exercise)
Convert Potato Pirates to Java

1) An enemy ship has 10 potato crew


members. It was attacked by the card
deck shown on the left. Show that there
are 4 potato crew members left.

2) An enemy ship has 20 potato crew


members. It is attacked by the card deck
shown on the left. Show that there are 2
potato crew members left.

© Copyright Codomo Pte Ltd 2022


29
While Loop (Exercise)
Convert Potato Pirates to Java
16

This is the
enemy

A B C

3) Which card deck can deal the highest damage to the enemy?
Convert all 3 decks into Java code.

© Copyright Codomo Pte Ltd 2022


30
If-Else and Switch
What is an if-else statement?
If-else statements help us write programs that can make decisions!
We use if-else statements everyday in our lives:
“If you are tired, sleep; or else, keep working” or “If you are hungry,
eat; or else, skip your meal”. Can you think of one more?

In Potato Pirates In Java

if (crew <= 4) {
System.out.println(“Fry”);
}
else {
System.out.println(“Mash”);
}

Type the code out in Eclipse and see what it does. Remember to
declare the variable “crew” first. When you’re done, we’ll take a
closer look at the if statement.

© Copyright Codomo Pte Ltd 2022


31
If-Else and Switch
Breakdown (if statement)
Let’s take a closer look at the structure of an if-else statement.
condition

if (crew <= 4)

if (crew <= 4) {
// code A
}
else {
// code B
}

Legend
Condition: A boolean expression. It will return True or False

Similar to the while loop, an if statement will execute an action


based on a condition. If a condition is true, it will run code A; else
it will run code B. It’s that simple. However, the if-else statement
differs from while loop; it only runs once.

While and For are loops, but If-Else is


a statement, so it only runs once!

© Copyright Codomo Pte Ltd 2022


32
If-Else and Switch
What is a switch statement?
A switch statement compares the value of a variable to the values
specified in case statements. It’s very similar to the if-else
statement. Let’s learn how to use it in Java!

In Potato Pirates

Get a new ship and a potato

Pick a card from the discard pile

Draw 3 cards

In Java
int crew = 2;
switch (crew) {
case 1:
System.out.println("get a new ship and a potato");
break;
case 2:
System.out.println("pick a card from the discard pile");
break;
case 3:
System.out.println("draw 3 cards");
break;
default:
System.out.println("you get nothing");
}

© Copyright Codomo Pte Ltd 2022


33
If-Else and Switch
Breakdown (switch statement)
The switch statement value is compared with the value of each
case. If there is a match, the corresponding case is executed.
Otherwise, the default case is executed.

Closer look value

switch(crew)
General Structure
switch (crew) {
case 1:
// code A
break;
case 2:
// code B
break;

Default:
// code C
}

Err… what is break?


The break statement is used to exit a control statement. Without it,
even if there’s a match between the value and the case, the code
will continue to run downward and make comparisons. This can
become a problem if your switch statement has many cases.
Hence, break!

© Copyright Codomo Pte Ltd 2022


34
If-Else and Switch (Exercise)
Convert Potato Pirates to Java

1) An enemy ship has 10 potato


crew members. It is attacked by
the card deck shown on the left.
Show that there are 7 potato
crew members left.

1) An enemy ship has 10 potato


crew members. It is attacked by
the card deck shown on the left.
Show that there are 6 potato
crew members left.

Let’s relax the “max 3 cards in


your hand” rule for a while.

© Copyright Codomo Pte Ltd 2022


35
If-Else and Switch (Exercise)
Convert Potato Pirates to Java

3) Create a switch statement which prints out the following


sentences based on how many crew members you have, assuming
that crew cannot have a negative value:
0 Potato : Print (“Gameover…”)
1 Potato : Print(“I am dying!”)
2 Potatoes: Print(“Am I dying?”)
3 Potatoes: Print(“I am an unlucky pirate”)
4 Potatoes: Print(“I shall not give up!”)
5 or more Potatoes: Print (“There’s nothing to worry about”)

© Copyright Codomo Pte Ltd 2022


36
Switch Syntax

switch(ships){ Switch
Java Syntax Cheat Sheet
statement

case 1:
While Loop Syntax If-else Loop Syntax
case 2: Condition
Actions

default: while (crew > 4){ Condition

} if (crew > 4) {
Action
} }
Actions
else{
For Loop Syntax Initialising Variables }
Increment/
Initialisation Decrement
Data Type: Value:

Data Types
for (int i=1;i<=3;i++){ int crew = 10;
} String → String
Action Variable name: Integer → int
Condition Character → char
Boolean → boolean
Java Keywords
Integer → String Integer.toString()

abstract continue for new switch


String → Integer Integer.valueOf()
assert default goto package synchronized
Character from variable.charAt()
boolean do if private this string

break double implements protected throw

byte else import public throws Comparison & Logical


Operators
case enum instanceof return transient
Equal ==
catch extends int short try
Not equal !=
char final interface static void
Less than <
class finally long strictfp volatile
Greater than >
const float native super while
Less than or equal <=

Greater than or equal >=


Addition/ Concatenation Subtraction Multiplication
And &&

+ - * Or ||

Division Remainder
Not !
Arithmetic
/ % Operators
37
Answer Sheet for Exercises
Variables

Getting & Updating Variable

1. 2. 3.
int x = 10; int a = 10; int b = 12;
x = x + 5; a = a / 2; b = b % 3;
System.out.println(x); System.out.println(a); System.out.println(b);

Mathematical Operators (Predict the answer without computer)


k=200, z=2, x=6 , y=13

String Concatenation & Indexing

1. 2.
String a = "Hello "; String word1 = "POTATO PIRATES";
String b = "Potato King"; char s_letter = word1.charAt(13);
System.out.println(a+b); System.out.println(s_letter);

Data Types
1.
String x = "10";
int x_int = Integer.valueOf(x);
System.out.println(x_int + 20);

2.
int y = 7;
String y_str = Integer.toString(y);
System.out.println(y_str + " Potato Kings");

© Copyright Codomo Pte Ltd 2022


38
Answer Sheet for Exercises
For loop

Basic Questions

1. 2.
for (int i=1; i<101; i++) { for (int i=3; i<21; i++) {
System.out.println(i); System.out.println(i);
} }

Convert Potato Pirates to Java

1.
int enemy_crew = 10;
for (int i=0; i<2; i++) {
enemy_crew = enemy_crew - 1;
}
System.out.println(enemy_crew);

2.
int y = 2;
int enemy_crew = 30;
for (int j=0; j<3; j++) {
for (int i=0; i<y; i++) {
enemy_crew = enemy_crew - 3;
}
}
System.out.println(enemy_crew);

3.
int enemy_crew = 10;
int enemy_left = 4;
int enemy_killed = enemy_crew-enemy_left;
int mash = 2;
int cards = enemy_killed/mash;

System.out.println(cards); //returns 3

4. 11, 12, 13, 14, or 15

© Copyright Codomo Pte Ltd 2022


39
Answer Sheet for Exercises
While loop

Basic Questions
1. 2.
int num = 10; int num = 10;
while (num >= 1) { while (num >= 5) {
System.out.println(num); System.out.println(num);
num = num - 1; num = num - 1;
} }

Predict the result (Do this without computer)


1. crew = 7 2. crew = 20

Convert Potato Pirates to Java


1. 2.
int enemy_crew = 10; int enemy_crew = 20;
while (enemy_crew > 4){ while (enemy_crew > 4){
enemy_crew = enemy_crew - 2; for (int i=0; i<3; i++) {
} enemy_crew = enemy_crew - 2;
System.out.println(enemy_crew); }
}
System.out.println(enemy_crew);

3a. 3b.
int crew = 16; int crew = 16;
while (crew > 5) { for (int i=0;i<3;i++){
crew = crew - 3; crew = crew - 3;
} }
System.out.println(crew); System.out.println(crew);

3c. Card deck A deals the highest


int crew = 16; damage.
for (int i=0;i<3;i++){
while (crew>5){
crew = crew - 1;
}
}
System.out.println(crew);

© Copyright Codomo Pte Ltd 2022


40
Answer Sheet for Exercises
If-else

Convert Potato Pirates to Java


1.
int enemy_crew = 10;
if (enemy_crew <= 5){
enemy_crew = enemy_crew - 2;
}
else{
enemy_crew = enemy_crew - 3;
}
System.out.println(enemy_crew);

2.
int enemy_crew = 10;
if (enemy_crew <= 5) {
for (int i=0; i<2; i++) {
enemy_crew = enemy_crew - 3;
}
}
else{
while (enemy_crew > 6) {
enemy_crew = enemy_crew - 2;
}
}
System.out.println(enemy_crew);

© Copyright Codomo Pte Ltd 2022


41
Answer Sheet for Exercises
If-else

Convert Potato Pirates to Java


1.
int crew = 10;
switch(crew) {
Case 0:
System.out.println("Gameover...);
break;
case 1:
System.out.println("I am dying!");
break;
case 2:
System.out.println("Am I dying?");
break;
case 3:
System.out.println("I am an unlucky pirate!");
break;
case 4:
System.out.println("I shall not give up!");
break;
default:
System.out.println("There's nothing to worry about.");
}

© Copyright Codomo Pte Ltd 2022


42
Ahoy Mateys!
Onward to our next voyage!

Spud-tech-cular treasures await at


https://potatopirates.game/

You might also like