Java 4_Loops

While loop

import java.util.Scanner; // Library that allows us to capture user input

public class LessonFour {
    
    // Creates a Scanner object that monitors keyboard input
    static Scanner userInput = new Scanner(System.in);
    
    public static void main(String[] args)
    {
        /*
         * The while loop : A while loop executes the code between {} until the 
          condition is no longer true
         */
        
        int i = 1;
        
        while(i < 20)
        {
            // Use continue to skip over printing 3
            if(i == 3)
            {
                i+=2; // When using continue, don't forget to change the iterator
                continue; // continue skips a loop iteration, but not the loop
            }
            
            System.out.println(i);
            i++;
            
            // Just print odd numbers
            if((i%2) == 0)
            {
                i++;
            }
            
            // i is greater than 10 jump out of the loop
            if(i > 10)
            {
                break; // Forces the program to leave the loop prematurely
            }
        }
}

Code that calculates the value for PI

     ```
    double myPi = 4.0; // My starting value for pi
    
    // Starting value for my loop iterator in the loop
    double j = 3.0; 
    
    // The while loop
    while(j<11)
    {
        // I calculate pi with this formula
        // PI = 4 - 4/3 + 4/5 - 4/7...
        myPi = myPi - (4/j) + (4/(j+2));
        j += 4;
        System.out.println(myPi);
    }

Execute while loop until the user quits it


        String contYorN = "Y";
        int h = 1;
        
        // equalsIgnoreCase checks if the input string is equal to y or Y
        while (contYorN.equalsIgnoreCase("y"))
        {
            System.out.println(h);
            System.out.print("Continue y or n?");
            contYorN = userInput.nextLine(); // Accepts a string input from the user
            h++;
            
        }

The do while loop

        int k = 1;
        
        do 
        {
            System.out.println(k);
            k++;
        } while (k <= 10); // Counts from 1 to 10

The for loop :

        for (int l=10; l >= 1; l--)
        {
            System.out.println(l);
        }
        
        for (m=1, n=2; m <= 9; m+=2, n+=2)
        {
            System.out.println(m + "\n" + n);
        }

Enhanced For Loop

int a[]={1,2,3,4,5}
sum=0;
for(int x: a){  //enhanced for loop just need the type 
                //the identifier and the array u wanna working through
sum+=a;
}
System.out.println(sum);

你可能感兴趣的:(Java 4_Loops)