In this document we are going to learn some additional concepts related with the control structures seen in this unit. We’ll see how to work with more complex loop structures, and some additional elements that we can add to these loops. Also, we will learn some basic rules to write clean code regarding these control structures.
The iterative structures that we have learnt in previous documents can be combined, so that we can place one of them inside another. This complex structure is also called nested loop. It can be a do..while inside a for, or a for inside another for, or any other combination.
For instance, the following code prints a square filled with asterisks, whose size is determined by variable size (we assume that this variable has been previously declared and assigned):
for (int i = 1; i <= size; i++)
{
for (int j = 1; j <= size; j++)
{
System.out.print("*");
}
System.out.println();
}
Exercise 1:
Write a program called Triangle in which we ask a user to enter a height (integer) and then we write a reversed triangle like the following one (assuming a height of 5):
*****
****
***
**
*
Exercise 2:
Create a program called Counter that asks the user to write numbers between 1 and 100. The program must keep asking the number until it is a number in the valid range. For each valid number, it must count from this number to 1 in descending order.
There are some special instructions that can be used inside loops to alter its natural behavior. These instructions are break and continue.
The break instruction exits the loop in which it is placed. For instance, this loop only counts from 1 to 5, because the break instruction exits before completing the whole count:
for (int i = 1; i <= 10; i++)
{
System.out.println(i);
if (i == 5)
break;
}
The continue instruction forces a new iteration of the loop, without running the instructions below it. For instance, this loop counts from 1 to 10, but it does not print number 5, because continue instruction goes back to the beginning of the loop when i is 5, without printing this value at the end of the loop:
for (int i = 1; i <= 10; i++)
{
if (i == 5)
continue;
System.out.println(i);
}
These two instructions are NOT recommended in our programs, since they can be easily avoided in order to make our code more understandable. In the first case, if we just want to count from 1 to 5, we should just define a for loop from 1 to 5. In the second case, if we don’t want to print number 5 in the screen, we can specify this condition in the if clause:
for (int i = 1; i <= 10; i++)
{
if (i != 5)
System.out.println(i);
}
In 01e previous documents we have seen some basic rules to write clean code, but now that we have learnt some additional concepts regarding control structures, our code can get a little bit more complex, and we need to apply some additional rules to keep it tidy.
Appropriate code formatting and spacing tells the reader that the programmer has paid attention to every single detail of the program. However, when we find a bunch of lines of code incorrectly indented and/or spaced, we may think that the same inattention may be present in other aspects of the code.
Let’s see some simple rules to format and space your code vertically:
import java.util.Scanner;
public class Program
{
public static void main(String[] args)
{
int personAge;
String personName;
Scanner sc = new Scanner(System.in);
System.out.println("Tell me your name:");
personName = sc.nextLine();
System.out.println("Tell me your age:");
personAge = sc.nextInt();
if (personAge > 18)
System.out.println("You are an adult, " + personName);
}
}
String personName;
/*
* This comment should not be written here!
*/
int personAge;
// Java style (opening brace is NOT considered a blank line)
if (condition) {
...
}
// C# style (opening brace can be considered a blank line)
public static void Main()
{
if (condition)
{
...
}
...
Regarding opening braces, you can decide which of these patterns you want to apply, but you must:
Regarding horizontal spacing or formatting, there are also some simple rules that we can follow.
if ((personAge > 18 && personAge <= 65) ||
(personName.equals("John")) || (personName.equals("Mary")))
{
...
}
int average = (number1 + number2) / 2;
StringBuilder longText;
int textSize;
String textToFindAndReplace;
public class MyClass
{
public static void main(String[] args)
{
System.out.println("Hello");
if (...)
{
System.out.println("Inside an if");
}
}
}