Page 481 - Introduction to Programming with Java: A Problem Solving Approach
P. 481
11.6 Embedded Assignments 447
line#
a
b
c
output
1
?
8
5
3
5
3
5
4
55 5
Embedding an Assignment within a Loop Condition
Exceptforapuremultipleassignmentlikea = b = c;it’sbesttoavoidembeddingmultipleassign- ments as expressions in other statements, because that makes code hard to understand. Nevertheless, it’s fairly common to embed a single assignment as an expression in a loop condition. For example, Figure 11.8 containsaprogramthataveragesasetofinputscores.Notethe(score = stdIn.nextDouble())
/*****************************************************************
*
AverageScore.java
Dean & Dean
This program averages input scores.
*****************************************************************/
Apago PDF Enhancer
public class AverageScore
*
*
*
import java.util.Scanner;
{
public static void main(String[] args)
{
double score;
double count = 0;
double totalScore = 0;
Scanner stdIn = new Scanner(System.in);
System.out.print("Enter a score (or -1 to quit): ");
while ((score = stdIn.nextDouble()) != -1)
{
}
// end AverageScore class
}
// end main
}
count++;
totalScore += score;
embedded assignment
System.out.print("Enter a score (or -1 to quit): ");
if (count > 0)
{
}
System.out.println("Average score = " + totalScore / count);
Figure 11.8 AverageScore program that demonstrates use of embedded assignments
⎧⎪
⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎨ ⎪ ⎪
⎪ ⎪ ⎪ ⎩