[programming] Decision-Making in JSP


The basic structure of Decision-Making in  PHP programming Language and JSP Programming language is exactly the same. ‘Decision-Making in JSP also use IF…ELSE and SWITCH…CASE statements.

IF … ELSE statement

Most of decision-making structure refer to this statement. This statement is suitable for small case (one/two condition(s)) of decision making until big case decision-making (nested if/more than 2 conditions).

Structure :

if (condition) {
statements;
}
else if {
statements ;
}
else {
statements;
}

Example :

<%! int day = 3; %>
<html>
<head><title>IF...ELSE Example</title></head>
<body>
<% if (day == 1 | day == 7) { %>
<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
<% } %>
</body>
</html>

Syntax above, show you that JSP scriptlet has the ability to embed its own code among HTML tags, just like another web programming language.

Or, you can use the whole JSP code. Example :

<%! int day = 3; %>
<html>
<head><title>IF...ELSE Example</title></head>
<body>
<%
if (day == 1 | day == 7) {
out.println(“<p> Today is weekend</p> “);
}
else {
out.println(“<p> Today is not weekend</p>“);
}
%>
</body>
</html>

Both codes will generate the same result. The same rule also work for more than two decisions-making. Example :

<%! int day = 3; %>
<html>
<head><title>IF...ELSE Example</title></head>
<body>
<% if (day == 1 | day == 7) { %>
<p> Today is weekend</p>
<% } else if (day <=6 || day >= 2) { %>
<p> Today is not weekend</p>
<% } else  { %>
<p> There is no day like this </p>
<% } %>
</body>
</html>

SWITCH…CASE

Beside IF…ELSE IF… ELSE structure for more-than-two decision-making, you can use SWITCH…CASE structure.

Structure :

switch(variable) {
case condition1 : statements;
case condition2 : statements;
case condition3 : statements;
default : statements;

Default works like ‘else’ in if structure.

example :

<%! int day = 3; %>
<html>
<head><title>SWITCH...CASE Example</title></head>
<body>
<%
switch(day) {
case 0:
out.println("It\'s Sunday.");
break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");
break;
case 4:
out.println("It\'s Thursday.");
break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It's Saturday.");
}
%>
</body>
</html>

4 thoughts on “[programming] Decision-Making in JSP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s