Programming and Problem Solving with Java

(やまだぃちぅ) #1
695

Formatting Lines and Expressions


Java allows you to break a long statement in the middle and continue onto the next line. The
split can occur at any point where it would be possible to insert spaces without affecting the
behavior of the code. When a line is so long that it must be split, it’s important to choose a
breaking point that is logical and reasonable. Compare the readability of the following code
fragments:


outFile.println(" for a radius of "+ radius + " the diameter of the cir"



  • "cle is "+ diameter);
    outFile.println(" for a radius of "+ radius +
    " the diameter of the circle is "+ diameter);


When writing expressions, keep in mind that spaces improve readability. Usually you
should include one space on either side of the == operator as well as most other operators.
Occasionally, spaces are left out to emphasize the order in which operations are performed.
Here are some examples:


if(x+y > y+z)
maximum = x + y;
else
maximum = y + z;
hypotenuse = Math.sqrt(aa + bb);


Indentation


The purpose of indenting statements in a program is to provide visual cues to the reader and
to make the program easier to debug. When a program is properly indented, the way the state-
ments are grouped is immediately obvious. Compare the following two program fragments:


while(count <= 10 )
{
num = Integer.parseInt(in.readLine());
if(num == 0 )
{
count++;
num = 1 ;
}
out.println(num);
out.println(count);
}

Free download pdf