Java Control Flow

Arrays and a “for each” loop in Java:

int intArray[] = new int[4];

intArray[0] = 2147483647;

intArray[1] = 65535;

intArray[2] = 7;

intArray[3] = intArray[2] * intArray[1];

for (int arrayElement : intArray){

System.out.println(arrayElement);

}

Java switch/case:

import java.util.Scanner;

public class Main{

public static void main(String[] args) throws InterruptedException{

int numberToGuess = 5;

Scanner userInput = new Scanner(System.in);

System.out.println(“I’m thinking of a number between 1 and 10”);

boolean guessedRight = false;

while (!guessedRight) {

System.out.print(“Enter your guess here: “);

int userGuess = userInput.nextInt();

switch (userGuess) {

case 0:

case 1:

case 2:

case 3:

case 4:

System.out.println(“Too low.”);

break;

case 5:

System.out.println(“You got it!”);

guessedRight = true;

break;

case 6:

case 7:

case 8:

case 9:

case 10:

System.out.println(“Too high.”);

break;

default:

System.out.println(“Invalid choice.”);

break;

}

}

}

}

Java if/else:

public class Main{

public static void main(String[] args){

if (5 > 2) {

System.out.println(“you will see this if the condition is true”);

} else if (9 < 100) {

System.out.println(“you see this if the first is not true”);

System.out.println(“but the second condition is true”);

} else {

System.out.println(“you see this if no condition is true”);

}

}

}

Java for loop:

public class Main{

public static void main(String[] args){

SweetPotato coolSpud = new SweetPotato(“Idaho”, “Chris”, 5, 2);

for (int i = 0; i < 10; i++){

coolSpud.grow();

}

System.out.println(coolSpud.weight);

}

}

Java while loop:

public class Main{

public static void main(String[] args){

SweetPotato coolSpud = new SweetPotato(“Idaho”, “Chris”, 5, 2);

int counter = 0;

while (counter < 10) {

coolSpud.grow();

System.out.printf(“Potato weight: %s\n”, coolSpud.weight);

counter++;

}

}

}

← Previous | Next →

Java Topic List

Main Topic List

Leave a Reply

Your email address will not be published. Required fields are marked *