1、Chapter 6More Conditionals and LoopsJava Software SolutionsFoundations of Program DesignSeventh Edition2More Conditionals and Loops Now we can fill in some additional details regarding Java conditional and repetition statements Chapter 6 focuses on:the switch statement the conditional operator the d
2、o loop the for loop drawing with the aid of conditionals and loops dialog boxes3OutlineThe switch StatementThe Conditional OperatorThe do StatementThe for StatementDrawing with Loops and ConditionalsDialog Boxes4The switch Statement The switch statement provides another way to decide which statement
3、 to execute next The switch statement evaluates an expression,then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches5The switch Statement The g
4、eneral syntax of a switch statement is:switch(expression)case value1:statement-list1 case value2:statement-list2 case value3:statement-list3 case .switchandandcasearearereservedreservedwordswordsIf If expressionmatches matches value2,control jumpscontrol jumpsto hereto here6The switch Statement Ofte
5、n a break statement is used as the last statement in each cases statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used,the flow of control will continue into the next case Sometimes this may be appropriate,but often we want to
6、execute only the statements associated with one case7The switch Statementswitch(option)case A:aCount+;break;case B:bCount+;break;case C:cCount+;break;An example of a switch statement:8The switch Statement A switch statement can have an optional default case The default case has no associated value a
7、nd simply uses the reserved word default If the default case is present,control will transfer to it if no other case value matches If there is no default case,and no other value matches,control falls through to the statement after the switch9The switch Statement The type of a switch expression must
8、be integers,characters,or enumerated types As of Java 7,a switch can also be used with strings You cannot use a switch with floating point values The implicit boolean condition in a switch statement is equality You cannot perform relational checks with a switch statement See GradeReport.java 10/*/Gr
9、adeReport.java Author:Lewis/Loftus/Demonstrates the use of a switch statement./*import java.util.Scanner;public class GradeReport /-/Reads a grade from the user and prints comments accordingly./-public static void main(String args)int grade,category;Scanner scan=new Scanner(System.in);System.out.pri
10、nt(Enter a numeric grade(0 to 100):);grade=scan.nextInt();category=grade/10;System.out.print(That grade is);continue11continue switch(category)case 10:System.out.println(a perfect score.Well done.);break;case 9:System.out.println(well above average.Excellent.);break;case 8:System.out.println(above a
11、verage.Nice job.);break;case 7:System.out.println(average.);break;case 6:System.out.println(below average.You should see the);System.out.println(instructor to clarify the material +presented in class.);break;default:System.out.println(not passing.);12continue switch(category)case 10:System.out.print
12、ln(a perfect score.Well done.);break;case 9:System.out.println(well above average.Excellent.);break;case 8:System.out.println(above average.Nice job.);break;case 7:System.out.println(average.);break;case 6:System.out.println(below average.You should see the);System.out.println(instructor to clarify
13、the material +presented in class.);break;default:System.out.println(not passing.);Sample RunEnter a numeric grade(0 to 100):91That grade is well above average.Excellent.13OutlineThe switch StatementThe Conditional OperatorThe do StatementThe for StatementDrawing with Loops and ConditionalsDialog Box
14、es14The Conditional Operator The conditional operator evaluates to one of two expressions based on a boolean condition Its syntax is:condition?expression1:expression2 If the condition is true,expression1 is evaluated;if it is false,expression2 is evaluated The value of the entire conditional operato
15、r is the value of the selected expression15The Conditional Operator The conditional operator is similar to an if-else statement,except that it is an expression that returns a value For example:larger=(num1 num2)?num1:num2);If num1 is greater than num2,then num1 is assigned to larger;otherwise,num2 i
16、s assigned to larger The conditional operator is ternary because it requires three operands16The Conditional Operator Another example:If count equals 1,the Dime is printed If count is anything other than 1,then Dimes is printedSystem.out.println(Your change is +count+(count=1)?Dime:Dimes);17Quick Ch
17、eckExpress the following logic in a succinct manner using the conditional operator.if(val=10)System.out.println(It is not greater than 10.);else System.out.println(It is greater than 10.);18Quick CheckExpress the following logic in a succinct manner using the conditional operator.if(val=10)System.ou
18、t.println(It is not greater than 10.);else System.out.println(It is greater than 10.);System.out.println(It is+(val=10)?not:)+greater than 10.);19OutlineThe switch StatementThe Conditional OperatorThe do StatementThe for StatementDrawing with Loops and ConditionalsDialog Boxes20The do Statement A do
19、 statement has the following syntax:do statement-list;while(condition);The statement-list is executed once initially,and then the condition is evaluated The statement is executed repeatedly until the condition becomes false21Logic of a do Looptruetrueconditionconditionevaluatedevaluatedstatementstat
20、ementfalsefalse22The do Statement An example of a do loop:The body of a do loop executes at least once See ReverseNumber.javaint count=0;do count+;System.out.println(count);while(count 0);System.out.println(That number reversed is +reverse);25continue System.out.print(Enter a positive integer:);numb
21、er=scan.nextInt();do lastDigit=number%10;reverse=(reverse*10)+lastDigit;number=number/10;while(number 0);System.out.println(That number reversed is +reverse);Sample RunEnter a positive integer:2896That number reversed is 698226Comparing while and dostatementstatementtruetruefalsefalseconditioncondit
22、ionevaluatedevaluatedThe while LooptruetrueconditionconditionevaluatedevaluatedstatementstatementfalsefalseThe do Loop27OutlineThe switch StatementThe Conditional OperatorThe do StatementThe for StatementDrawing with Loops and ConditionalsDialog Boxes28The for Statement A for statement has the follo
23、wing syntax:for(initialization;condition;increment)statement;The The initializationis executed onceis executed oncebefore the loop beginsbefore the loop beginsThe The statement is isexecuted until theexecuted until thecondition becomes false becomes falseThe The increment portion is executed at port
24、ion is executed at the end of each iterationthe end of each iteration29Logic of a for loopstatementstatementtruetrueconditionconditionevaluatedevaluatedfalsefalseincrementincrementinitializationinitialization30The for Statement A for loop is functionally equivalent to the following while loop struct
25、ure:initialization;while(condition)statement;increment;31The for Statement An example of a for loop:for(int count=1;count 0;num-=5)System.out.println(num);A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance See Multiples.java
26、See Stars.java33/*/Multiples.java Author:Lewis/Loftus/Demonstrates the use of a for loop./*import java.util.Scanner;public class Multiples /-/Prints multiples of a user-specified number up to a user-/specified limit./-public static void main(String args)final int PER_LINE=5;int value,limit,mult,coun
27、t=0;Scanner scan=new Scanner(System.in);System.out.print(Enter a positive value:);value=scan.nextInt();continue34continue System.out.print(Enter an upper limit:);limit=scan.nextInt();System.out.println();System.out.println(The multiples of +value+between +value+and +limit+(inclusive)are:);for(mult=v
28、alue;mult=limit;mult+=value)System.out.print(mult+t);/Print a specific number of values per line of output count+;if(count%PER_LINE=0)System.out.println();35continue System.out.print(Enter an upper limit:);limit=scan.nextInt();System.out.println();System.out.println(The multiples of +value+between +
29、value+and +limit+(inclusive)are:);for(mult=value;mult=limit;mult+=value)System.out.print(mult+t);/Print a specific number of values per line of output count+;if(count%PER_LINE=0)System.out.println();Sample RunEnter a positive value:7Enter an upper limit:400The multiples of 7 between 7 and 400(inclus
30、ive)are:71421283542495663707784919810511211912613314014715416116817518218919620321021722423123824525225926627328028729430130831532232933634335035736437137838539239936/*/Stars.java Author:Lewis/Loftus/Demonstrates the use of nested for loops./*public class Stars /-/Prints a triangle shape using aster
31、isk(star)characters./-public static void main(String args)final int MAX_ROWS=10;for(int row=1;row=MAX_ROWS;row+)for(int star=1;star=row;star+)System.out.print(*);System.out.println();37/*/Stars.java Author:Lewis/Loftus/Demonstrates the use of nested for loops./*public class Stars /-/Prints a triangl
32、e shape using asterisk(star)characters./-public static void main(String args)final int MAX_ROWS=10;for(int row=1;row=MAX_ROWS;row+)for(int star=1;star=row;star+)System.out.print(*);System.out.println();Output*38Quick CheckWrite a code fragment that rolls a die 100 times and counts the number of time
33、s a 3 comes up.39Quick CheckWrite a code fragment that rolls a die 100 times and counts the number of times a 3 comes up.Die die=new Die();int count=0;for(int num=1;num=100;num+)if(die.roll()=3)count+;Sytem.out.println(count);40The for Statement Each expression in the header of a for loop is optiona
34、l If the initialization is left out,no initialization is performed If the condition is left out,it is always considered to be true,and therefore creates an infinite loop If the increment is left out,no increment operation is performed41For-each Loops A variant of the for loop simplifies the repetiti
35、ve processing of items in an iterator For example,suppose bookList is an ArrayList object The following loop will print each book:for(Book myBook:bookList)System.out.println(myBook);This version of a for loop is often called a for-each loop42For-each Loops A for-each loop can be used on any object t
36、hat implements the Iterable interface It eliminates the need to retrieve an iterator and call the hasNext and next methods explicitly It also will be helpful when processing arrays,which are discussed in Chapter 843Quick CheckWrite a for-each loop that prints all of the Student objects in an ArrayLi
37、st object called roster.44Quick CheckWrite a for-each loop that prints all of the Student objects in an ArrayList object called roster.for(Student student:roster)System.out.println(student);45OutlineThe switch StatementThe Conditional OperatorThe do StatementThe for StatementDrawing with Loops and C
38、onditionalsDialog Boxes46Drawing Techniques Conditionals and loops enhance our ability to generate interesting graphics See Bullseye.java See BullseyePanel.java See Boxes.java See BoxesPanel.java 47/*/Bullseye.java Author:Lewis/Loftus/Demonstrates the use of loops to draw./*import javax.swing.JFrame
39、;public class Bullseye /-/Creates the main frame of the program./-public static void main(String args)JFrame frame=new JFrame(Bullseye);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);BullseyePanel panel=new BullseyePanel();frame.getContentPane().add(panel);frame.pack();frame.setVisible(true);4
40、8/*/Bullseye.java Author:Lewis/Loftus/Demonstrates the use of loops to draw./*import javax.swing.JFrame;public class Bullseye /-/Creates the main frame of the program./-public static void main(String args)JFrame frame=new JFrame(Bullseye);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Bullseye
41、Panel panel=new BullseyePanel();frame.getContentPane().add(panel);frame.pack();frame.setVisible(true);49/*/BullseyePanel.java Author:Lewis/Loftus/Demonstrates the use of conditionals and loops to guide drawing./*import javax.swing.JPanel;import java.awt.*;public class BullseyePanel extends JPanel pr
42、ivate final int MAX_WIDTH=300,NUM_RINGS=5,RING_WIDTH=25;/-/Sets up the bullseye panel./-public BullseyePanel()setBackground(Color.cyan);setPreferredSize(new Dimension(300,300);continue50continue /-/Paints a bullseye target./-public void paintComponent(Graphics page)super.paintComponent(page);int x=0
43、,y=0,diameter=MAX_WIDTH;page.setColor(Color.white);for(int count=0;count NUM_RINGS;count+)if(page.getColor()=Color.black)/alternate colors page.setColor(Color.white);else page.setColor(Color.black);page.fillOval(x,y,diameter,diameter);diameter-=(2*RING_WIDTH);x+=RING_WIDTH;y+=RING_WIDTH;/Draw the re
44、d bullseye in the center page.setColor(Color.red);page.fillOval(x,y,diameter,diameter);51/*/Boxes.java Author:Lewis/Loftus/Demonstrates the use of loops to draw./*import javax.swing.JFrame;public class Boxes /-/Creates the main frame of the program./-public static void main(String args)JFrame frame=
45、new JFrame(Boxes);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);BoxesPanel panel=new BoxesPanel();frame.getContentPane().add(panel);frame.pack();frame.setVisible(true);52/*/Boxes.java Author:Lewis/Loftus/Demonstrates the use of loops to draw./*import javax.swing.JFrame;public class Boxes /-/C
46、reates the main frame of the program./-public static void main(String args)JFrame frame=new JFrame(Boxes);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);BoxesPanel panel=new BoxesPanel();frame.getContentPane().add(panel);frame.pack();frame.setVisible(true);53/*/BoxesPanel.java Author:Lewis/Lof
47、tus/Demonstrates the use of conditionals and loops to guide drawing./*import javax.swing.JPanel;import java.awt.*;import java.util.Random;public class BoxesPanel extends JPanel private final int NUM_BOXES=50,THICKNESS=5,MAX_SIDE=50;private final int MAX_X=350,MAX_Y=250;private Random generator;/-/Se
48、ts up the drawing panel./-public BoxesPanel()generator=new Random();setBackground(Color.black);setPreferredSize(new Dimension(400,300);continue54continue /-/Paints boxes of random width and height in a random location./Narrow or short boxes are highlighted with a fill color./-public void paintCompon
49、ent(Graphics page)super.paintComponent(page);int x,y,width,height;for(int count=0;count NUM_BOXES;count+)x=generator.nextInt(MAX_X)+1;y=generator.nextInt(MAX_Y)+1;width=generator.nextInt(MAX_SIDE)+1;height=generator.nextInt(MAX_SIDE)+1;continue55continue if(width=THICKNESS)/check for narrow box page
50、.setColor(Color.yellow);page.fillRect(x,y,width,height);else if(height=THICKNESS)/check for short box page.setColor(Color.green);page.fillRect(x,y,width,height);else page.setColor(Color.white);page.drawRect(x,y,width,height);56OutlineThe switch StatementThe Conditional OperatorThe do StatementThe fo
侵权处理QQ:3464097650--上传资料QQ:3464097650
【声明】本站为“文档C2C交易模式”,即用户上传的文档直接卖给(下载)用户,本站只是网络空间服务平台,本站所有原创文档下载所得归上传人所有,如您发现上传作品侵犯了您的版权,请立刻联系我们并提供证据,我们将在3个工作日内予以改正。