Java intermedio
Jim White
Java Developer
if-elseif (bonus == 10000) {
System.out.println("Let's buy a car!");
} else if (bonus == 5000) {
System.out.println("Let's take a trip!");
} else if (bonus == 1000) {
System.out.println("Let's save!");
}
switch (expression) {
case value1: // if (expression == value1)
// statements
case value2: // if (expression == value2)
// statements
// usa tantos case como necesites
}
char direction = 'N';
switch (direction) {
case 'E':
System.out.println("We are headed east.");
case 'S':
System.out.println("We are headed south.");
case 'W':
System.out.println("We are headed west.");
case 'N':
System.out.println("We are headed north."); // Esto se imprimiría
}
char direction = 'W';
switch (direction) {
case 'E':
System.out.println("We are headed east.");
case 'S':
System.out.println("We are headed south.");
case 'W':
System.out.println("We are headed west."); // Esto se imprimiría
case 'N':
System.out.println("We are headed north."); // Esto también se imprimiría
}
break permite agrupar varios casos:
char direction = 'N';
switch (direction) {
case 'E':
case 'W':
System.out.println("We are headed east or west.");
break;
case 'S':
case 'N':
System.out.println("We are headed south or north.");
break;
}
We are headed south or north.
default opcional al final de un switchdefault debe ser el último caso en un switchdefault es una forma de tener un caso «para los demás valores»char direction = 'z';
switch (direction) {
case 'E':
case 'W':
System.out.println("To east or west.");
break;
case 'S':
case 'N':
System.out.println("To south or north.");
break;
default:
System.out.println("We are lost.");
}
We are lost.
char character = 'A';
if (character == 'A') {
System.out.println("It's A");
} else if (direction =='B') {
System.out.println("It's B");
} else {
System.out.println("Unknown");
}
int, byte, short, char o Stringchar character = 'A';
switch (character) {
case 'A':
System.out.println("It's A");
break;
case 'B':
System.out.println("It's B");
break;
default:
System.out.println("Unknown");
}
Java intermedio