COMPSCI4039: Programming
Loops and String formatting
public class Integers {
Copyright By PowCoder代写 加微信 powcoder
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...
3x1=3 3x2=6 3x3=9 3 x 4 = 12 3 x 5 = 15 etc
COMPSCI4039: Programming
Loops 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?
¡ñ What¡¯s the difference?
¡ñ It might help to think of an initial value of i that would give different
behaviour?
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: Programming
Loops 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
¡ñ Here¡¯s 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,8
for(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 loop¡¯s 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: Programming
Loops and String formatting
Infinite loops
¡ñ It¡¯s 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
¡ñ Here¡¯s our example using an infinite loop and break
public class ForLoop {
public static void main(String[] args) {
int i = 0;
for(;;) { // infinite loop
System.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) doesn¡¯t 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('\n¡¯); }
A slightly more complex example
¡ñ Let¡¯s 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 won¡¯t seem quite so daunting
Breaking the prime numbers problem down
Work in small groups if you like
Break the problem down as far as you can
Which bits do you think you can / cannot implement? Have a go at implementing this in the lab
Note: this is an example of an algorithm. You will see more of this in ADS (semester 2)
COMPSCI4039: Programming
Loops and String formatting
When concatenation isn¡¯t 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.0
Clifford 1000000 1.56
Miles Davis 123 1 Clifford 1000000
0.6667 1.0000 1.5600
String.format
¡ñ String.format is a method that allows us to combine Strings and numbers with
control 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 the
following people:
¡ð Bill (5 years old)
¡ð Cuthbert (10 years old)
¡ð Eve (103 years old)
String.format
¡ñ If we concatenate:
¡ð System.out.println(name + ¡° ¡° + age);
¡ñ It won¡¯t 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
¡ñ Here¡¯s a possible String.format command for this problem
¡ð String line = String.format("%15s %5d",name,age); ¡ñ String.formatpassesusbackaString
¡ð Here, I¡¯m defining a String called line to store the result
¡ñ The format string has one term per thing we want to
display (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 be
displayed (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 doesn¡¯t 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 any
modification
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 part
to make it length 5
¡ñ All padding is spaces
Bill 5 Cuthbert 10 Eve 103
An alternative:
String line = String.format("%-15s %05d",name,age); Bill 00005
Cuthbert 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代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com