Slide 1 - Mathematics & Computing Science

advertisement
Lecture 8: Bits and Pieces
Tami Meredith
Roadmap
 Today's lecture has a bit of everything.
 Going back over previous chapters and pulling out
little bits I haven't covered yet or did not cover in much
depth
 Providing gentle introductions to things you don't
really need to know, but that you should be aware that
they exist
 Lots and lots of exercises 
Methods
 Buildings are too big to be designed in a single drawing
 Architects design houses in parts – a basement floor plan, a




first floor plan, an exterior (lot) plan, and so on ...
Programs are also too big to be designed as a single part
We break programs into parts – these parts are called
methods
A method is PART of a program – it will not execute/run by
itself
Methods need data to work:
 Input – from other parts of the program, via parameters
 Output – to other parts of the program, via the return value
A Method
public static
{
if ((val %
return
} else {
return
}
boolean isEven (int val)
2) == 0) {
(true);
(false);
 Input: val, of type int
 Output (return value): a boolean
 This method is only part of a program, it won't work by
itself
 A named block of code, the block is called isEven
Exercise
 Write a method that takes two strings and returns (as a
new string) the longest common prefix of both strings
 E.g., the longest prefix of "Money" and "Motion" is
"Mo"
 The method should be case sensitive
Solution
// Note: Fails if si is a prefix of sj
public static String lcp (String s1, String s2)
{
int i = 0;
while (s1.charAt(i) == s2.charAt(i))
{
i++;
}
return (s1.substring(0,i));
}
Variable Modification
 We can modify variables in several ways:
Assignment: x = 7; y = 3 * x;
2. Increment/Decrement: x++; --y;
3. Combined assignment and an operation: x += 1;
This is called compound assignment.
 The compound operators are: +=, -=, *=, /=, %=
(there are more, &=, <<=, etc.)
 x += 1; is the same as x = x + 1;
 y *= x; is the same as y = y * x;
1.
Increment/Decrement (Review)
Expression
Alternative
i++;
i = i + 1;
++i;
i = i + 1;
i--;
i = i – 1;
--i;
i = i – 1;
j = i++;
j = i;
i = i + 1;
j = ++i;
i = i + 1;
j = i;
j = i--;
j = i;
i = i - 1;
j = --i;
i = i – 1;
j = i;
Incrementing X
 There are a lot of ways to increment a variable:
1. x++;
2. ++x;
3. x = x + 1;
4. x += 1;
 It is only when ++ is used in another expression that

its location (before or after the variable) becomes
important
in this example it does not matter and all four
expressions are identical
Expressions vs. Statements
 Expressions
 generate a value that can be used in an assignment
 can also be used as function arguments
 e.g., 3+4, x-y, max(a,b), data.length
 Statements
 perform an action but do not generate a value
 e.g., while (true) { ... }, println();
Conditional Expressions
 An expression with a condition
 Generate a value, can be used in assignments
 Format: (test) ? true-value : false-value
 Examples
diff = (x > y) ? x-y : y-x;
max = (x > y) ? x : y;
mean = (n == 0) ? 0 : sum/n;
Syntactic Sugar
 The statement
mean = (n == 0) ? 0 : sum/n;
 Is really just a compact way of saying
if (n == 0)
mean = 0;
else
mean = sum/n;
 The term syntactic sugar is used to refer to optional (not
really needed) constructs that make code "sweeter" to read
 Compound assignment is another example of syntactic
sugar, e.g., x += 7; is the same as x = x + 7;
Precedence
 There is a complex precedence (order of operations)
for Java's operators
 DON'T rely on it, DON'T waste a lot of effort
memorising it
 INSTEAD – use parentheses (i.e., '(' and ')') liberally
to make things happen in the order that you want
 Parentheses also make things much clearer as well as
avoiding surprise/errors due to precedence
See: Text
Fig 3.9
Shifts
 It is possible to work with the individual bits of a value
 This is an advanced technique that is used to create
more efficient code (save time or space)
 We will not be doing any shifts, but you should know
that they exist
byte x = 9;
x = x << 2;
x = x >> 1;
// x = 0000 1001;
// x = 0010 0100;
// x = 0001 0010;
Bitwise Operations
 Like shifts, bitwise operations work on the specific bits
of a value
 They are another advanced tool that you won't need in
this course, but are useful to be aware of
 NOTE:
 & is not the same as &&, will generate different results
 | is not the same as ||, will generate different results
 ^ is an operator
 Knowing they are here and different will help you find
and hopefully avoid mistakes
Keyboard Input (Review)




It is useful to get input from the user
Until now we have provided the code to do this for you
System.in is an object of type InputStream
It is not very useful since you can only read bytes from
an InputStream
 We apply a Scanner to the InputStream to
1. Break the stream into meaningful parts (e.g.,
integers, lines, words)
2. Change the parts into useful types (e.g., ints,
floats, Strings)
Useful Methods
 See Figure 2.7 (Page 98) of the text
 next(), gets the next word
 nextLine(), gets the next line, discards the newline
 nextInt(), gets the next integer
 hasNextLine(), checks if there is another line, returns a
boolean
 hasNextInt(), checks if there is another int, returns a
boolean
 There are many other methods you can use, see:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
 You need to know the delimiter – what ends a word, an
integer, etc.
Example (Code Fragments)
import java.util.Scanner;
// <OR> import java.util.*;
Scanner scn= new Scanner(System.in);
String line;
if (scn.hasNextLine()) {
line = scn.nextline();
}
Exercise
 Write a program that asks the user for a pair of integers
and prints all the even numbers (in increasing order)
between the two integers
 The output should be on one line and separated by
commas
 Example:
Enter the first number: 11
Enter the second number: 4
4, 6, 8, 10
Solution
import java.util.Scanner;
public class evens {
public static void main (String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("Enter the first integer: ");
int i1 = keyboard.nextInt();
System.out.print("Enter the second integer: ");
int i2 = keyboard.nextInt();
int start = (i1 < i2) ? i1 : i2;
start = ((start % 2) == 0) ? start : start + 1;
int end = (i2 > i1) ? i2 : i1;
end = ((end % 2) == 0) ? end : end – 1;
for (int i = start; i <= end; i += 2) {
System.out.print(i);
if (i != end) System.out.print(", ");
}
System.out.println("");
} // end main()
} // end class evens
Wrapper Classes
 Every primitive type has a class
 E.g., ints are associated with Integer
 The class can be used when we need to treat the int as a





class
The class also has a set of useful static methods we can call
to manipulate integers for us
e.g., Integer.parseInt(String) converts a String into
an int
See: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html
Figure 2.9 (page 123) provides other methods for converting
Strings into primitive types
Wrapper classes are not important to learn at this point ...
Example (Code Fragments)
import java.util.*;
Scanner keyboard = new Scanner(System.in);
String number = keyboard.next();
/* There is a way to identify when the
* conversion fails so we can try
* something else */
int n = Integer.parseInt(number);
Short-Circuit Evaluation
 Recall: x && y is true when both x and y are true
 If x is false, it really doesn't matter what y is – the
expression can never be true
 To save time, y is never examined if x is false!
 This behaviour is called short circuit evaluation
 We can use this to our benefit ...
if (keyboard.hasNext() && (word = keyboard.next()))
{
System.out.println("Read: " + word);
}
More Short Circuitry
 Recall: x || y is true if x is true or y is true
 If x is true, it doesn't really matter what y is since the
expression will always evaluate to true
 To save effort, we never examine y if x is true
 Example
if ((s.length() > 0) || (s = "Empty"))
{
System.out.println("String is: " + s);
}
ASCII
 Every character has a value
 We store the value, not the character
 We can treat characters as numbers as a consequence
 The values assigned are based on the ASCII encoding
 0-127:
Basic ASCII
 128-255: Extended ASCII
 256-65535: Unicode (subsumes ASCII)
Hexidecimal
 Our ASCII table had "hex" values
 Hexidecimal is base 16
 Digits are 0, 1, ... , 0, A, B, C, D, E, F (lower case is OK)
 Hex is used a lot by programmers because 16 is a power
of 2 and can be represented by 4 bits
 Again, you don't need to know it, but being aware that
it exists is useful
 Prefix hex constants with 0x
 int x = 0x10; // x = hexidecimal 10 = 16;
Exercise
 Write a program that prints out the letters of the
alphabet in the following format:
A, a
B, b
C, c
...
Z, z
 Note, you don't need hexidecimal for this (or any)
exercise, I mentioned it so you'd know what Hex
meant in the ASCII table
Solution
public class alphabet {
public static void main (String[] args) {
char lower = 'a', upper = 'A';
do {
System.out.println(
upper++ + ", " + lower++);
} while (upper <= 'Z');
} // end main()
} // end class alphabet
Solution (alternative)
public class alphabet {
public static void main (String args) {
char lower = 'a', upper = 'A';
for (; upper <= 'Z'; upper++, lower++)
{
System.out.println(upper + ", " + lower);
}
} // end main()
} // end class alphabet
Exercise
 Write a program that asks a user for an integer from 1
to 26 and then prints out the equivalent letter of the
alphabet (e.g., 'a' for 1, 'b' for 2)
 E.g.,
Enter an integer: 10
Character 10 is j
Solution
public class letters {
public static void main (String[] args) {
Scanner keyboard = new Scanner (System.in);
int input;
char c;
System.out.print("Enter an integer: ");
i = keyboard.nextInt();
if ((i < 1) || (i > 26)) {
System.out.println("Value was not in range (1..26)");
} else {
c = (char) (i + '`'); // c = (char) (i + 96);
System.out.println("Character " + i + " is " + c);
}
} // end main(()
} // end class letters
Keep Going! We're getting there 
To Do
 Go to the lab and complete Assignment 7
 Read and re-read Chapters 1-4, and 7 – know this
material VERY well
 Keep working on Chapters 5, 6 - most of Chapter 6 we
have not covered, nor the part of Chapter 5 on objects
and classes
 Practice, Practice, Practice
Download