Switch Statements: Integers
Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SwitchWithInts {
public static void main(String[] args) {
String input = getInput("Enter a number between 1 and 12: ");
int month = Integer.parseInt(input);
switch (month) {
case 1:
System.out.println("The month is January");
break; //must use break to leave switch
case 2:
System.out.println("The month is February");
break;
case 3:
System.out.println("The month is March");
break;
default:
break;
}
}
private static String getInput(String prompt) {
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
System.out.print(prompt);
System.out.flush();
try {
return stdin.readLine();
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
}
Switch Statements: Enums
Project > New > Enum
Code:
public enum Month {
JANUARY, FEBRUARY, MARCH; //Constants of enum class
}
public class SwitchWithEnums {
// Enumerations
public static void main(String[] args) {
// int month = 1;
Month month = Month.FEBRUARY;
switch(month) {
case JANUARY:
System.out.println("It's the first month");
break;
case FEBRUARY:
System.out.println("It's the second month");
break;
case MARCH:
System.out.println("Its the third month");
}
}
}
Switch Statements: Strings (Java SE7)
Loops
Code:
public class Main {
static private String[] months =
{"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"};
public static void main(String[] args) {
// using counter variables instead of complex objects
// for (int i = 0; i < months.length; i++) {
// System.out.println(months[i]);
// }
// For each month in the months[] array
// for (String month : months) {
// System.out.println(month);
// }
// eval BEFORE loop
// int counter = 0;
// while (counter < months.length) {
// System.out.println(months[counter]);
// counter ++;
// }
// eval AFTER loop
int counter = 0;
do {
System.out.println(months[counter]);
counter ++;
} while (counter < months.length);
}
}
- Log in to post comments