Unit 4 Iteration Notes
A Boolean expression is a Java expression that returns a Boolean value: true or false
Rather than implementing mathematical operators such as "+" or "-", comparative or boolean operators such as "==" or "!" can be used.
In Java two if statements could be used if both if statement conditions could be true at the same time.
Java supplies a primitive data type called Boolean, instances of which can take the value true or false only
import java.lang.Math;
import java.util.Scanner;
public class NumberGuess {
private int answer;
private int guess;
Scanner in = new Scanner(System.in);
public NumberGuess() {
this.answer = (int) Math.floor(Math.random()*10 + 1);
System.out.println(answer);
}
public void play() {
while (answer != guess) {
this.getGuess();
}
in.close();
}
public void getGuess() {
System.out.print("Guess a number 1-10: ");
this.guess = in.nextInt();
System.out.println(this.guess);
if (this.guess > this.answer) {
System.out.println("too high");
} else if (this.guess < this.answer) {
System.out.println("too low");
} else {
System.out.println("congrats");
}
}
public static void main(String[] args) {
NumberGuess num = new NumberGuess();
num.play();
}
}
For Loop: A loop that iterates through its index
for (int i = 0; i<100; i+=3) {
System.out.println(i);
}
0 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99
Enhanced For Loop: Used to iterate through arrays.
int[] arr = {93, 24, 4, 3, 87,545,76,12,64,30};
for (int i : arr) {
System.out.println(i);
}
93 24 4 3 87 545 76 12 64 30
While Loop: Runs as long as a boolean condition is true and has the boolean condition checked before each iteration is ran Do While Loop: Similar to a While loop, however, the conditon is only checked after each iterative portion of the code is ran --> the code will execute at least one action.
int i = 0;
// printing even numbers with while loop
while (i < 1100) {
System.out.println(i);
i += 8;
}
0 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 128 136 144 152 160 168 176 184 192 200 208 216 224 232 240 248 256 264 272 280 288 296 304 312 320 328 336 344 352 360 368 376 384 392 400 408 416 424 432 440 448 456 464 472 480 488 496 504 512 520 528 536 544 552 560 568 576 584 592 600 608 616 624 632 640 648 656 664 672 680 688 696 704 712 720 728 736 744 752 760 768 776 784 792 800 808 816 824 832 840 848 856 864 872 880 888 896 904 912 920 928 936 944 952 960 968 976 984 992 1000 1008 1016 1024 1032 1040 1048 1056 1064 1072 1080 1088 1096
Nested Loops: Loops placed within each other, creating better iteration, most optimal for 2D arrays
int[][] arr = {
{6, 9, 33},
{27, 43, 94},
{4, 35, 2}
};
for (int i = 0; i<arr.length; i++) {
for (int j = 0; j<arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
6 9 33 27 43 94 4 35 2