Re: java - What are 'if-else' and 'while' statements
"Brittany" <brit.hall@veri zon.net> wrote in message
news:5L3Db.115$ UF5.38@nwrdny01 .gnilink.net...[color=blue]
>
> can someone explain to me what if else staments do and
> what while statements do.
>[/color]
This, really, is the task of text books and tutorials. For starters, try:
This beginner Java tutorial describes fundamentals of programming in the Java programming language
However, here is a quick, highly simplistic, explanation:
public static void main(String[] args)
{
// Point A
...
// Do this ...
// Do that ...
// Do something else ...
...
// Point B
}
A program starts execution at Point A, and proceeds, line by line, towards
Point B; this is known as serial execution since one step follows the other
in a serial, or sequential, fashion.
This behaviour may be suitable for many tasks, but there are situations in
which you may wish to vary this behaviour, in particular, by:
* Wanting to offer a choice as to which step [or
series of steps] is performed next
* Wanting to repeat a step [or series of steps],
a number of times
It is in order to achieve these things - provide some choice as to which
steps get peformed next - that 'if-else' and 'while' statements [among
others] exist.
Take, for example, a simple temperature program in which each step is
performed serially:
// (3)
System.out.prin tln("Temperatur e is: " + currentTemperat ure);
}
This program is fairly straightforward to understand - each step follows the
other in sequence. Now, say, the program should also print out whether the
temperature is above, or below, freezing. This involves:
* Testing the temperature value to see whether it is above
or below freezing
* Executing the relevant code that goes along with each
alternative
// (3)
System.out.prin t("Temperatur e is: " + currentTemperat ure);
// (4a)
if (currentTempera ture < FREEZING)
// (4b)
System.out.prin tln(" and it is below freezing");
else
// (4b)
System.out.prin tln(" and it is at, or above freezing");
}
Clearly, the step [i.e. code executed] performed after (4a) is *one of* the
(4b) alternatives - the 'if-else' statement has allowed a choice to be made
as to what is done next.
Now, say the program is to only print the current teperature while the
temperature is above freezing. As with the 'if-else' statement there is a
need to:
* Test the temperature value to see whether it is above
or below freezing
* Executing the relevant code
The chief difference is that since the expected behaviour is to be
repetitive, the test part needs to be repeated too, that is, it is necessary
to repeatedly get the temperature, and test to see whether it is above or
below freezing. The following code does this:
Hopefully this gives you a rough idea what both the 'if-else' and 'while'
statements do. I do, however, urge you to seek further explanations in a
text book or tutorial.
Comment