Just like in Alice or AppInventor it is often useful to
use loops to repeat code statements. Even if something is being
repeated just 2x, it is useful to use loops because:
- Makes coding faster
- Better readability
- If you make a change to your code in the loop, you change it
in one place.
The two main types of loops are
while (condition is true)
are in the format: for (this counter variable staring here, while
this condition met, do this to the counter)
for (int i=0; i<10; i++)
System.out.println("We are at" + i);
this would repeat the inside 10 times (while i was 0 through 9)
Exiting (not used all that often, just reference)
To exit the current loop, you use the statement:
Lets create these methods: HERE IS STARTER CODE
- public void printTurtleFor() that will print I love Turtles 50 times.
Do this with a for loop
- public void printIllegalWhile() that will print Illegal Character 50 times.
Do this with a while loop
- public void printNumbers(int max) that will print the numbers
from 1 to max on one line like 1,2,3,4,5,6,7,....,150 [if max
was 150] (note: no comma at end)
- public void printOdds(int start, int end) that will print the
odd numbers from start to end; assume start is odd. (note you wont use scanner.)
- public void insultUser() that will insult the user and then
say do you want another insult (y or n) if they say y it will
repeat, if they so n it will end. [advanced - have it choose from 1 of 5 insults randomly]
- extra credit:
- public void puzzleNumber() that will solve this
puzzle: how many numbers between 1-1000 have a product of their
digits greater than 50 like 439 is 4*3*9 which is greater than
50. Print out all the numbers and say how many there were.
- Print out the first 30 prime numbers [you will need to know % (modulo operator) which gives the remainder, like 5%2 is 1 or 40%8=0 or 13%5 =3 or 24%5=4]
- Find the smallest positive integer that if it is divided by 7, 9, and 11 the
remainders are 1, 2, and 3 respectively.
- Find all the two-digit prime numbers with the product of its digits equal to a