A Java Approach: Selection Structures - Use Cases



Hello everyone and welcome back! Up to now we have been concerned to make as complete an overview as possible of the fundamental concepts we need to approach the use of conditional structures. We have therefore introduced the concept of conditional structures, outlining the various situations that could arise. We then went on to outline the main features of Boolean algebra, analysing the use of Boolean variables and Boolean operators.

One concept that is worth repeating is that conditional structures, also called flow control structures, serve to modify the normal flow of program execution. 

Since learning to program is not enough to read, let's go and analyse some practical examples so that we can see in action the concepts we have analysed so far. It must be said that, in examining some examples, I will take for granted the theoretical and practical aspects concerning the variables, focusing on the aspects concerning the selection structures.

Case 1: Nested selection structures

A first question that could be asked is the case of the nested selection structures. One might wonder whether a second if can be grafted within an if. 

The answer is yes.

Let's see how.

// check that n1 is greater than or equal to n2
if (n1 >= n2) {
    // check that n1 is greater than or equal to n3
    if (n1 >= n3) {
        largest = n1;
    }
    else {
        largest = n3;
    }
} else {
// check that n2 is greater than or equal to n3
    if (n2 >= n3) {
        largest = n2;
    }
    else {
        largest = n3;
    }
}
System.out.println("Largest Number: " + largest);

This example may seem complex on the surface, but if we read it carefully, we realize that the task it performs is quite simple: it is concerned with finding the variable that has the maximum value within a set of three variables. 

To do this, the reasoning is as follows: to be the maximum, one value must be greater than the other two. So what happens is that you check if n1 is greater than n2. If this is true, then you check that n1 is also greater than n3. If two conditions are also true, then you value the variable largest with the value contained in n1. 

If n1 is less than n2, we know that n1 cannot be the maximum. The check with n2 and n3 therefore remains to be done. If n2 is greater than n3, then n2 is the maximum of the three variables. Otherwise, the maximum is n3.

We can easily see that it is possible to engage more if one inside the other. This is allowed, though not always encouraged. 

Syntax note: the curly brackets

Technically, Java allows us to omit the curly brackets from both the if blocks and the other blocks, as long as they contain only one instruction and no more.

Often this practice is used, and I admit that I do it myself: it has to be said that, in my opinion, we are losing legibility and clarity. Obviously, we are going to gain in compactness of the code. In the case of nested ifs, I recommend using them all the time.

Case 2: Selection structures with composite conditions

Another interesting case to analyse is the one where Boolean operators are used within the conditions. The classic example that can be analysed is one where you want to check that a given number falls within a range. Think, for example, of a software to make statistical evaluations of the school performance of a class.

Suppose we want to count how many grades are sufficient on a scale from 1 to 10, i.e. with a value greater or equal to six.

So let's see how we can do this, assuming we have already declared and initialised a variable called grade.

int counter = 0;
if( grade >= 6 && grade <= 10){
    counter = counter + 1;
}

The idea is therefore that a grade should be considered sufficient if and only if it is greater than or equal to 6 and at the same time less than or equal to 10. On a first attempt, someone might argue that a simple grade check >= 6 is sufficient. The problem arises, however, if there is an insertion error and a grade greater than ten is inserted. Our application would consider it sufficient, even if it is not a valid grade. One would then find oneself considering legitimate a situation that should be handled as a problem.

Case 3: condition with negation

Often, it may be convenient to use conditions that contain a denial within them. This may be for different reasons. It may be developmental convenience or mere readability. 

Let's see an example. As a case of use we can always keep the case of grade analysis. Let's assume that we want to check that a grade is valid. A solution might be similar to the one produced before. A far more readable and simple solution, in my opinion, is the following.

boolean voteValid = vote >= 6 && vote <= 10;
if(!voteValid){
    //Manage error
}

So we notice that the code here is very easy to understand. In natural language, the condition can be read as "if not votoValido", which translated into Italian natural language, can be "if the vote is not valid". So we understand that the if will be executed only if the vote is not valid. This is the case when using a Boolean variable greatly simplifies code development.

Conclusions

This brief examination leaves us with some salient aspects. In particular, let us see how operators can be combined to form complex expressions. 

It is important, in these situations as in the rest of programming, to pay attention to code indentation. The risk is to write a code that is very complicated to read, if you don't insert the necessary spacing at the beginning of the line.

We will see later on that there is a valid alternative to the massive use of if constructs: the switch statement. 

It should be pointed out and reiterated that the analysis made is by no means exhaustive. The idea is to first give the fundamental tools to start writing code, and then to deepen some peculiar aspects.

To practice, it may be useful to solve the following exercise:

Write a SmallEven program that asks the user to enter a whole number and displays the message "Even and Small" if the number is even and is between 0 and 100, otherwise it prints the message "Not even and small". (Note: this program can be done using nested if-else or Boolean expressions. Try both versions).

The exercise comes from the  following document.

 
 
Alessio Mungelli

Alessio Mungelli

Computer Science student at UniTo (University of Turin), Network specializtion, blogger and writer. I am a kind of expert in Java desktop developement with interests in AI and web developement. Unix lover (but not Windows hater). I am interested in Linux scripting. I am very inquisitive and I love learning new stuffs.

 
 
 

Related Posts

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

A Java approach: boolean variables

The previous time, we talked extensively about Boolean variables, trying to outline the main operations that can be carried out at a practical level.  Of all the cases examined, we have…

A Java approach: condtional structures

Hello everyone and welcome back! The previous times we have introduced the concept of variable, trying to define some basic concepts about it.  However, some situations suggest that the concept of…

Hashmap: hashing, collisions and first functions

Today we are going to study some concepts closely related to hashmaps. The concepts we are going to see are hashing and collisions. Hashing The idea of hashing with chaining is to…

Hashmap: Overflow Lists

In this short series of articles we will go to see how it is possible to create the Hashmap data structure in C. In the implementation we're going to use the…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

Data structures in Java - Linked Lists

With 2020 we are going to look at a new aspect of programming: data structures. It is often the case that everyone uses structures provided by the various programming languages.…

A Java approach: variables - use case

Hello all friends and welcome back! After the introduction made on the variables, we try to analyse some critical issues that may arise in quite common situations. Let's start by analysing…

A Java approach: variables

Hello everyone and welcome back! Today we will begin a journey that will lead us to study, and possibly review, what are the basics of programming. We will start by talking…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration