For, While, Nested Loops

  • while loop
    • executed while something is happening
    • iterates over elements
    • can be infinite if boolean is always true
  • do-while loop

    • condition is checked after executed statements
  • for loop

    • certain amt of loops thru code block
  • nested loop: loop w/in loop

  • for-each loop

    • traverses an array in java

While Loop

int x = 10;

while (i<10) {
    System.out.println(i);

    i++;
}
public class arrays
{
   public static void main(String[] args)
   {
   }}
   public static void main(String[] args) {
    int[] numbers = {2, 4, 6, 8, 10};
    int i = 0;
    while (i < numbers.length) {
        System.out.println(numbers[i]);
        i++;

    }}

Do-While Loop

int i = 0;
do {
  System.out.println(i);
  i++;
}
while (i < 5);
0
1
2
3
4

For/For-Each Loop

for (int i = 5; i < 14; i++) {
    System.out.println(i);
  }

  for (int j = 1; j <= 3; j++) {
    System.out.println(j);
}//nested loop
5
6
7
8
9
10
11
12
13
1
2
3
//for-each loop
int arr[]={10,20,30,40,50};  
for(int j:arr){  
  System.out.println(j);  
}
10
20
30
40
50

HOMEWORK

//unit 4 hw
//number guesser
import java.util.Scanner;
import java.lang.Math;
 
Scanner number = new Scanner(System.in); 
float num_float = Integer.parseInt(number.nextLine());  // reads input
System.out.println(num_float);

double random = Math.random() * 10;
System.out.println(random);

public class Number{
    public static void main(String[] args){

        while (num_float != random){

            if (num_float < random){
                System.out.println("too low. higher");
                // Scanner number = new Scanner(System.in); 
                float num_float = Integer.parseInt(number.nextLine());  
                System.out.println(num_float);
            }

            if (num_float > random){
                System.out.println("too high. lower");
                Scanner number = new Scanner(System.in); 
                float num_float = Integer.parseInt(number.nextLine());  
                System.out.println(num_float);
            }
            
           
    }

    System.out.println("you got it!");
    



    }

}
Number.main(null)
---------------------------------------------------------------------------
java.lang.NumberFormatException: For input string: ""
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
	at .(#15:2)