Loops

Your Basic while Loop
The most basic of all looping statements in Java is while. The while statement creates a type of loop that’s called a while loop, which is simply a loop that executes continuously as long as some conditional expression evaluates to true. while loops are useful in all sorts of programming situations, so you use while loops a lot.

The while statement
The basic format of the while statement is like this:
while (expression)
statement
The while statement begins by evaluating the expression. If the expression is true, statement is executed. Then, the expression is evaluated again, and the whole process repeats. If the expression is false, statement is not executed, and the while loop ends.
Note that the statement part of the while loop can either be a single statement or a block of statements contained in a pair of braces. Loops that have just one statement aren’t very useful, so nearly all the while loops you code use a block of statements. (Well, okay, sometimes loops with a single statement are useful. It isn’t unheard of. Just not all that common.)
A counting loop
Here’s a simple program that uses a while loop to print the even numbers from 2 through 20:
public class EvenCounter
{
public static void main(String[] args)
{
int number = 2;
while (number <= 20)
{
System.out.print(number + “ “);
number += 2;
}
System.out.println();
}
}
If you run this program, the following output is displayed:
2 4 6 8 10 12 14 16 18 20

The conditional expression in this program’s while statement is number <= 20. That means the loop repeats as long as the value of number is less than or equal to 20. The body of the loop consists of two statements. The first prints the value of number followed by a space to separate this number from the next one. Then, the second statement adds 2 to number.

The Famous for Loop
In addition to while and do-while loops, Java offers one more kind of loop: the for loop.
The basic principle behind a for loop is that the loop itself maintains a counter variable — that is, a variable whose value is increased each time the body of the loop is executed. For example, if you want a loop that counts from 1 to 10, you’d use a counter variable that starts with a value of 1 and is increased by 1 each time through the loop. Then, you’d use a test to end the loop when the counter variable reaches 10. The for loop lets you set this up all in one convenient statement.
People who majored in Computer Science call the counter variable an iterator.
They do so because they think we don’t know what it means. But we know perfectly well that the iterator is where you put your beer to keep it cold.

The for loop follows this basic format:
for (initialization-expression; test-expression; countexpression)
statement;

The three expressions in the parentheses following the keyword for control how the for loop works. The following paragraphs explain what these three expressions do:
✦ The initialization expression is executed before the loop begins. Usually, you use this expression to initialize the counter variable. If you haven’t declared the counter variable before the for statement, you can declare it here too.
✦ The test expression is evaluated each time the loop is executed to determine whether the loop should keep looping. Usually, this expression tests the counter variable to make sure it is still less than or equal to the value you want to count to. The loop keeps executing as long as this expression evaluates to true. When the test expression evaluates to false, the loop ends.
✦ The count expression is evaluated each time the loop executes. Its job is usually to increment the counter variable.

Here’s a simple for loop that displays the numbers 1 to 10:
public class CountToTen
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
System.out.println(i);
}
}
This for loop apart has the following pieces:
✦ The initialization expression is int i = 1. This expression declares a variable named i of type int and assigns it an initial value of 1.
✦ The test expression is i <= 10. As a result, the loop continues to execute as long as i is less than or equal to 10.
✦ The count expression is i++. As a result, each time the loop executes, the variable i is incremented.
✦ The body of the loop is the single statement System.out. println(i). As a result, each time the loop executes, the value of the i variable is printed.

If Statements

Using If Statements
The if statement is one of the most important statements in any programming language, and Java is no exception. The following sections describe the ins and outs of using the various forms of Java’s powerful if statement.

Simple if statements
In its most basic form, an if statement lets you execute a single statement or a block of statements only if a boolean expression evaluates to true. The basic form of the if statement is this:

if (boolean-expression)
statement

Note that the boolean expression must be enclosed in parentheses. Also, if you use only a single statement, it must end with a semicolon. But the statement can also be a statement block enclosed by braces. In that case, each statement within the block needs a semicolon, but the block itself doesn’t.

Here’s an example of a typical if statement:
double commissionRate = 0.0;
if (salesTotal > 10000.0)
commissionRate = 0.05;

In this example, a variable named commissionRate is initialized to 0.0, and then set to 0.05 if salesTotal is greater than 10,000.

Here’s an example that uses a block rather than a single statement:
double commissionRate = 0.0;
if (salesTotal > 10000.0)
{
commissionRate = 0.05;
commission = salesTotal * commissionRate;
}
In this example, the two statements within the braces are executed if salesTotal is greater than 10000.0. Otherwise, neither statement is executed.

Logical Operators

Operator Name Description
! Not Returns true if the operand to the right evaluates to
false. Returns false If the operand to the right is true.

& And Returns true if both of the operands evaluate to true.
Both operands are evaluated before the And operator is applied.

I Or Returns true if at least one of the operands evaluates to true.
Both operands are evaluated before the Or operator is applied.

&& Conditional And Same as &, but if the operand on the left returns false,
returns false without evaluating the operand on the right.

II Conditional Or Same as I, but if the operand on the left returns true, returns true without evaluating the operand on the right.

Relational Operators

Operator Description
== Returns true if the expression on the left evaluates to the same value as the right expression.

!= Returns true if the expression on the left does not evaluate to the same value as
the expression on the right.

< Returns true if the expression on the left evaluates to a value that is less than the value of the expression on the right.

<= Returns true if the expression on the left evaluates to a value that is less than or equal to the expression on the right. > Returns true if the expression on the left evaluates to a
value that is greater than the value of the expression on the right.

>= Returns true if the expression on the left evaluates to a
value that is greater than or equal to the expression on the right.

Mathematical Functions

The Math class defines a number of methods that provide trigonometric, logarithmic, exponential, and rounding operations, among others. This class is primarily useful with floating-point values. For the trigonometric functions, angles are expressed in radians. The logarithm and exponentiation functions are base e, not base 10. Here are some examples:

double d = Math.toRadians(27); // Convert 27 degrees to radians
d = Math.cos(d); // Take the cosine
d = Math.sqrt(d); // Take the square root
d = Math.log(d); // Take the natural logarithm
d = Math.exp(d); // Do the inverse: e to the power d
d = Math.pow(10, d); // Raise 10 to this power
d = Math.atan(d); // Compute the arc tangent
d = Math.toDegrees(d); // Convert back to degrees
double up = Math.ceil(d); // Round to ceiling
double down = Math.floor(d); // Round to floor
long nearest = Math.round(d); // Round to nearest

Converting String Input to Numbers Example

/*************************************************
Name: Payroll.java
Output: Prints out total salary to the console using JOptionPane and System.out methods
Date: November 23, 2008
Author: Mr. P
*************************************************/

import javax.swing.*;
public class Payroll{ public static void main(String [] args)
{
int numOfHours;
String numOfHours_str;

double hourlyWage, totalSalary;
String hourlyWage_str;

numOfHours_str = JOptionPane.showInputDialog ("How many hours did you work this week?");
numOfHours = Integer.parseInt (numOfHours_str);

hourlyWage_str = JOptionPane.showInputDialog ("What is your hourly wage?");
hourlyWage = Double.parseDouble (hourlyWage_str);

totalSalary = numOfHours * hourlyWage;

JOptionPane.showMessageDialog (null,"Your total salary for this week is: $" +totalSalary);
System.out.println("Your total salary for this week is: $" +totalSalary);
}
}

String Literals

The String class represents text as a string of characters. Since programs usually communicate with their users through the written word, the ability to manipulate strings of text is quite important in any programming language. In some languages, strings are a primitive type, on a par with integers and characters. In Java, however, strings are objects; the data type used to represent text is the String class.
Because strings are such a fundamental data type, Java allows you to include text literally in programs by placing it between double-quote (") characters.
For example:

String name = "David";
System.out.println("Hello, " + name);

The Java Swing Classes
Java’s Swing classes create graphical objects on a computer screen. The objects can include buttons, icons, text fields, check boxes, and other good things that make windows so useful.
The name “Swing” isn’t an acronym. When the people at Sun Microsystems were first creating the code for these classes, one of the developers named it “Swing” because swing music was enjoying a nostalgic revival. And yes, in addition to String and Swing, the standard Java API has a Spring class.

Dialog Boxes

A dialog box is a small graphical window that displays a message to the user or requests input. You can quickly display dialog boxes with the JOptionPane class.

Message Dialog – A dialog box that displays a message; an OK button is also displayed.
Input Dialog – A dialog box that prompts the user for input and provides a text field where input is typed; and OK button and Cancel button are also displayed.

To display message dialogs the showMessageDialog method is used. The following statement calls that method:

JOptionPane.showMessageDialog(null, “Hello Class”);

Example:

String name;
name = JOptionPane.showInputDialog(“Enter your name”);

Converting String Input to Numbers

The JOptionPane class does not have different methods for reading values of different data types. The showInputDialog method always returns the user’s input as String, even if the user enters numeric data. For example if the user enters the number 72 into an input dialog, the showInputDialog method will return the string “72”. This can be a problem if you wish to use the user’s input in a math operation because you can not perform math on strings. In such a case, you must convert the input to a numeric value. To convert a string value to a numeric value, you use one of the methods listed below.

Examples:

1)
int number;
String str;

str = JOptionPane.showInputDialog(“Enter a number.”);
number = Integer.parseInt (str);

2)
double price;
String str;
str = JOptionPane.showInputDialog(“Enter the retail price.”);
price = Double.parseDouble (str);

_____________________________________________________