Download presentation
Presentation is loading. Please wait.
Published byGertrude George Modified over 9 years ago
1
AP CS
2
Enhanced for loop for(object type, declared object) This loop is not necessarily iterative. It is ideal to traverse array arrays and array lists
3
double[] num = new double[10]; // pretend they already have value If we wanted to print out the values for standard for loop for(int i = 0; i < num.size; i++) System.out.print(num[i]); Now, with the shorthanded loop for(double i : num) System.out.print(i);
4
ArrayList num1 = new ArrayList<>(); // pretend we have many entries for(i = 0; i < num1.size(); i++) System.out.print(num1.get(i)); for(Integer i : num1) System.out.print(i);
5
The switch statement Whenever you ask for input, you may have to decide what to do with that input. Currently, your decision might look like this: if(decision == 1) // code else if(decision == 2) //code else if(decision ==3). else
6
Let’s do this: // suppose variable condition is an integer switch(condition) { case 1://perform an action break; case 2://perform an action break; case 3://perform an action break default://perform an action }
7
int choice; System.out.println(“Please enter a choice “); choice = keyboard.nextInt(); switch(choice) { case 1:choice = choice +10; break; case 2:choice = choice / 15; break; case 3:choice = (int)(Math.random()*100); break; default:System.out.println(“There is no choice”); }
8
The break statement The break statement will take you out of any loop/conditional no matter what is going on. while(true) { System.out.println(“Hello World”); break; } do { break; System.out.println(“Hello World”); }
9
More break statements for(int k = 0; k < 100; k++) { if(k == 50) break; System.out.println(“Hello World”); }
10
The printf() The printf() statement has built in parameters that you can take advantage of to easily format your output. For example, what if you wanted 5 endlines? System.out.println(); System.out.printf(“\n\n\n\n\n”);
11
prinft() has some of the following features: You can out put floating point numbers and indicate their precision You can left or right justify your output You can set flags that will automatically modify output Example: What if you wanted to right justify an output by 10 spaces: System.out.println(“ “ + num1); System.out.printf(%10d, num1);
12
What if you wanted to format a decimal number. Suppose num1 = 8.326545110 I want to display only two decimals long: System.out.printf(%.2f, num1); //output8.32 What if I want to display 2 decimals long and justify it 10 spaces to the right? System.out.printf(%10.2f, num1); //output 8.32
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.