Just like other languages, Java has support for if-then-else, switch case, for loop and while loop.
Here is an example of an if-then-else:
if (x <= 1336) {Can you interpret the example? Every number less than or equal to 1336 is considered too low, and every number greater than or equal to 1338 is considered too high. A number between 1336 and 1338 (probably 1337 :P) is the right solution.
System.out.println("Too low!");
} else if (x >= 1338) {
System.out.println("Too high!");
} else {
System.out.println("You got it!");
}
A few things you should remember:
- The if expression must be enclosed within round brackets () and it must return a boolean value.
- The curly brackets {} are optional if there is only 1 statements inside. However it is a good practice to always use them.
When you are comparing a variable against many values you can use a switch case instead of multiple if-then-else. Here's an example of switch case:
switch (x) {Note that the break is important. Without it the control flow will fall through to the next case.
case 1336:
System.out.println("A little too low!");
break;
case 1338:
System.out.println("A little too high!");
break;
case 1337:
System.out.println("You got it!");
break;
default:
System.out.println("So far :P");
break;
}
Most of the time when working on a challenge you will need loops to do something repeatedly. In Java you can use 2 types of loop: for loop and while loop.
The for loop is usually used when counting is involved. For example, the following code prints all the numbers from 0 to 1337:
for (int i = 0; i <= 1337; i++)The for loop consists of 3 parts:
System.out.println(i);
- The first part (int i = 0) is the initialization. It initializes the value at the beginning of the loop.
- The second part (i <= 1337) is the termination condition. When its value is false the loop will terminate.
- The last part (i++) is the increment. After each iteration of the loop is done this statement will be executed once.
int i = 0;Basically you can do everything with just the for loop. But for convenience you might want to use the while loop too:
for (;;) {
System.out.println(i);
if (i > 1337) break;
i++;
}
int i = 0;Here is another variation of the while loop, with the condition checked at the end of each iteration:
while (i <= 1377) {
System.out.println(i);
i++;
}
int i = 0;You can use break inside while loops too:
do {
System.out.println(i);
i++;
} while (i <= 1337);
int i = 0;
while(true) {
System.out.println(i);
i++;
if (i > 1337) break;
}