[SOLVED] CS COMPSCI4039: Programming

$25

File Name: CS_COMPSCI4039:_Programming.zip
File Size: 254.34 KB

5/5 - (1 vote)

COMPSCI4039: Programming
Loops and String formatting

public class Integers {

Copyright By Assignmentchef assignmentchef

public static void main(String[] args) {
int i = 0; System.out.println(i); i++; System.out.println(i); i++; System.out.println(i); i++; System.out.println(i); i++; System.out.println(i); i++; System.out.println(i); i++; System.out.println(i); i++; System.out.println(i); i++; System.out.println(i); i++; System.out.println(i); i++;
You will often find you want to repeat a particular operation a certain number of times.
E.g. printing out all of the integers from 0 to 9?
There must be an easier way, right?

Java has several types of loop to help us with
repetitive tasks.
do loops
while loops
for loops
To understand them we need to combine our knowledge of conditions and compound statements

// some operations
} while(condition);
Repeatedly performs the operations within the { } until condition is false (i.e. while condition is true)
In our example:
the operations would be printing and increasing i
the condition would test if i<=9 (i is less than or equal to 9) Our example as a do loop Much neater! public class DoLoop {public static void main(String[] args) {int i = 0; do {System.out.println(i);}while(i<=9);Class exercise Write a program (all in a main method) that will, for any particular integer, print out the first ten terms of its times table. Do this using a do loop Example output for the integer 3 shown below…3×1=3 3×2=6 3×3=9 3 x 4 = 12 3 x 5 = 15 etc COMPSCI4039: ProgrammingLoops and String formatting A word on loops in general Our do loop consisted of: a compound statement (the stuff in the loop) a stopping condition All loops follow the same pattern As with any compound statement, scope rules apply In particular, variables created in the loop are not visible outside… while loops while(condition) {// some operations Very similar, except the condition is now at the top. Our example now looks like this: public class WhileLoop {public static void main(String[] args) {int i = 0; while(i<=9) {System.out.println(i);do versus while Look at the two examples Looks a bit pointless to have both? Whats the difference? It might help to think of an initial value of i that would give differentbehaviour?public class DoLoop {public static void main(String[] args) {int i = 0; do {System.out.println(i);}while(i<=9); public class WhileLoop {public static void main(String[] args) {int i = 0; while(i<=9) {System.out.println(i);Stopping conditions Our examples have used int counters to decide when to stop Any condition can be used. For example, can you work out what this does? import java.util.Scanner;public class SimonOnly {public static void main(String[] args) {Scanner s = new Scanner(System.in); boolean acceptable = false; while(!acceptable) {System.out.println(“Please enter your name:”); String name = s.nextLine(); if(name.equals(“Simon”)) {acceptable = true;System.out.println(“Welcome, Simon”); }COMPSCI4039: ProgrammingLoops and String formatting Counter loops Loops that change some variable at each iteration (e.g. i++) are very common They have their own type of loop: for loops for loops look a bit different to do and while loops Heres our example as a for loop: public class ForLoop {public static void main(String[] args) {for(int i=0;i<=9;i++) { System.out.println(i); The general syntax is: for( , , )
variable: the variable to use for the loop, and its initialisation (it can also be
declared here or declared earlier (e.g. for(int i=0; or for(i=0;)
condition: the condition that has to be true for the loop to continue
Change: how the variable should be changed at each iteration Most often i++ (if variable is i), but can be anything else.
for(int i=0;i<=9;i++) // 0,1,2,3,4,5,6,7,8,9 for(int i=9;i>=0;i) // 9,8,7,6,5,4,3,2,1,0 for(int i=0;i<=9;i+=4) // 0,4,8for(int i=1;i<=20;i*=5) // ? for(int i=0;i<=20;i*=5) // ? In do loops, the compound statement is run at least once In while and for, it might not be E.g. for(int i=10;i<9;i++) If we declare the variable e.g. for(int i=0;…) it only exists in the loops scope. Many programmers keep i, j, k, etc as loop variables and use them for nothing else We can also leave all things blank: for(;;)//thisgivesusaninfiniteloop!! COMPSCI4039: ProgrammingLoops and String formatting Infinite loops Its surprisingly easy to make loops that never end for(int i=0;i<20;i*=5) // i is always 0! In Eclipse, stop them by clicking on the red square Sometimes we might do it on purpose and stop the loop with a break statement (e.g. for(;;)) break: jump out of the current loop Heres our example using an infinite loop and break public class ForLoop {public static void main(String[] args) {int i = 0;for(;;) { // infinite loopSystem.out.println(i); i += 1;if(i == 9) {// jump out when we get to 9 continue: jump straight to the next iteration (if there is one) E.g. print only the even numbers Odd numbers have a non- zero remainder when divided (integer) by 2 public class ForLoop {public static void main(String[] args) {for(int i=0;i<=9;i++) { if(i % 2 != 0) {continue; }System.out.println(i); } Continue skips to the next iteration, missing the print line Loops within loops (within loops) What does this do? Remember: System.out.print(a) doesnt add a newline character public class LoopInLoop {public static void main(String[] args) {for(int i=1;i<=5;i++) { for(int j=1;j<=i;j++) {System.out.print(‘*); }System.out.print(‘
); }A slightly more complex example Lets write a program to list all of the prime numbers between 2 and an integer entered by the user A prime number is a number that is exactly divisible by just 1 and itself. E.g.3,7,11,… You will design the program and then implement it in the lab Maybe this seems tricky / daunting? The key thing is to break it down into small problems / tasks And then break them down some more… …the small bits wont seem quite so daunting Breaking the prime numbers problem downWork in small groups if you likeBreak the problem down as far as you canWhich bits do you think you can / cannot implement? Have a go at implementing this in the labNote: this is an example of an algorithm. You will see more of this in ADS (semester 2) COMPSCI4039: ProgrammingLoops and String formatting When concatenation isnt enough Concatenation lets us combine numbers and text together Sometimes we want more control over the output E.g. when making a table Miles Davis 123 0.6666666666666666 1 1.0Clifford 1000000 1.56 Miles Davis 123 1 Clifford 10000000.6667 1.0000 1.5600 String.format String.format is a method that allows us to combine Strings and numbers withcontrol over: Padding Number of digits after decimal point We pass to the method a formatting string and the values to be inserted For example, say we want to make a table of names and ages for thefollowing people: Bill (5 years old) Cuthbert (10 years old) Eve (103 years old) String.format If we concatenate: System.out.println(name + + age); It wont work well because the names and ages are different lengths:Bill 5 Cuthbert 10 Eve 103 String.format will let us fix the width of both fields String.format Heres a possible String.format command for this problem String line = String.format(“%15s %5d”,name,age); String.formatpassesusbackaString Here, Im defining a String called line to store the result The format string has one term per thing we want todisplay (here 2: name and age) Each term starts with a percent sign (%) followed by(in this case) a number and a letter. After the format String, we pass the things to bedisplayed (has to be as many as there are terms) String.format String line = String.format(“%15s %5d”,name,age); s means String. I.e. the first term will be a String (name) 15 is the length. I.e. we want to use at least 15 characters If the String is shorter than 15 characters, it gets padded If longer, it is left as is (it doesnt get truncated) Bill becomes ~~~~~~~~~~~Bill (~ = spaces, 11 of them) Cuthbert becomes ~~~~~~~Cuthbert (7 spaces) We can pad before (default) or after: Bill becomes Bill~~~~~~~~~~~ Or simply use %s to get the String without anymodification String.format Formatting integers Gets the integer as it is Pads the integer with spaces to give a length of at least 5 (23 becomes ~~~23) Adds padding after the integer (23 becomes 23~~~) We can also change the padding character to a zero: Pads with zero (0) instead of spaces (23 becomes 00023) String.format String line = String.format(“%15s %5d”,name,age); In our example we pad the String part to make it length 15 and the int partto make it length 5 All padding is spacesBill 5 Cuthbert 10 Eve 103 An alternative:String line = String.format(“%-15s %05d”,name,age); Bill 00005Cuthbert 00010 Eve 00103 String.format – doubles For double variables, we use %f Pads to at least length 5 with 2 digits after the decimal point: E.g. 3.1415 becomes ~3.14 (note the . counts as one of the characters) %7.2f 3.1415 becomes ~~~3.14 %7.3f 3.1415 becomes ~~3.142 (note the rounding) As with integers %05.2f pads with 0 rather than space %-5.2f does the padding after the number CS : assignmentchef QQ: 1823890830 Email: [email protected]

Reviews

There are no reviews yet.

Only logged in customers who have purchased this product may leave a review.

Shopping Cart
[SOLVED] CS COMPSCI4039: Programming
$25