Upload
darleen-porter
View
218
Download
3
Embed Size (px)
Citation preview
CS 121Week 3 - Wednesday
Last time
What did we talk about last time? Math methods Lab 2
Questions?
Project 1
System.out.format()
For Project 1, the easiest way to print out data with 2 decimal places is put "%.2f" in the formatting string for System.out.format()
If you want, you can include other things in the formatting string
double x = 5.74961;System.out.format("%.2f", x); //prints 5.75
System.out.format("Total = $%.2f", 15.7777); //prints Total = $15.78
Review of math methods
Methods
A method is a piece of Java code that has been packaged up so that you can use it over and over
Usually, a method will take some input and give some output
System.out.println() is an example of a method
Using a method (calling a method) always requires parentheses
Method example with sin()
The sin() method allows you to find the sine of an angle (in radians)
This method is inside the Math class The answer that it gives back is of
type double To use it, you might type the
following:
double value = Math.sin( 2.4 );
If your method takes input, you put it inside the
parentheses, if not, you leave them
empty
Next, you must give the method name that you
are calling
Unless the method is inside your class, you must supply a
class name and a dot
You can store the result of the
method, as long as the variable
matches the type that the method
gives back
Method syntax
result = class.method( input );
Other Math methodsReturn type
Name Job
double sin( double theta ) Find the sine of angle theta
double cos( double theta ) Find the cosine of angle theta
double tan( double theta ) Find the tangent of angle theta
double exp( double a ) Raise e to the power of a (ea)
double log( double a ) Find the natural log of a
double pow( double a, double b ) Raise a to the power of b (ab)
long round( double a ) Round a to the nearest integer
double random() Create a random number in [0, 1)
double sqrt( double a ) Find the square root of a
double toDegrees( double radians ) Convert radians to degrees
double toRadians( double degrees ) Convert degrees to radians
Operations on booleans
Operations on booleans
The boolean type seems so simple What on earth would we want to do
with it? Just like numerical types, we can
combine booleans in various ways You might be familiar with these
operations if you have taken a course in logic
The ! operator
The NOT operator Changes a true into a false or a false into a true
x !x
true false
false true
Combining boolean values
We can combine statements in logic together to make other interesting statements
The way we combine them makes a difference, e.g. Politicians lie.
(True) Cast iron sinks. (True)
Politicians lie in cast iron sinks.(Absurd)
The && operator
The AND operator It gives back true only if both things
being combined are true If I can swim AND the pool is not
filled with acid, then I will survivex y x && y
true true true
true false false
false true false
false false false
The || operator
The OR operator It gives back true if either or both
things being combined are true If I get punched in the face OR
kicked in the stomach, then I will be in pain x y x || y
true true true
true false true
false true true
false false false
The ^ operator
The XOR operator, sort of like what people often mean when they say "or" in English
It gives back true if one but not both things are true
If I get 1 apple XOR 3 oranges, then I will have an odd number of fruit
x y x ^ y
true true false
true false true
false true true
false false false
See how you're following…
(!true && (false^(false||true)))
Is this expression true or false?
It's false
Short circuit evaluation
In some circumstances, Java doesn't check the whole expression:
(true || (some complicated expression)) Ignores everything after || and gives
back true
(false && (some complicated expression)) Ignores everything after && and gives
back false
Operations on char values
What kinds of operations would you expect on chars?
Multiplication and division don't seem to make sense
We can increment and decrement a char
char letter;
letter = 'x'; // letter contains 'x'letter++; // letter contains 'y'letter++; // letter contains 'z'letter++; // letter contains ?
Sometimes it's useful to know the number
It is possible to convert a char into an int
It can be more useful to get the offset from a starting point
int number;number = 'a'; // letter contains 97
char letter = 'r';int number;number = letter – 'a' + 1;
//number is 18
ASCII Table
Everything in the computer is 1's and 0's
Each character has a number associated with it
These numbers can be listed in tables
The ASCII table only covers 7 bits of information (0-127)
NEVER EVER TYPE THESE NUMBERS IN CODE
Escape sequences
Remember that we use single quotes to designate a char literal: 'z'
What if you want to use the apostrophe character ( ' )? apostrophe: '\''
What if you want to use characters that can't be printed, like tab or newline? tab: '\t' newline: '\n'
The backslash is a message that a special command called an escape sequence is coming
Escape sequences in String literals
You can put escape sequences into String literals as well
You do not have to escape apostrophes in a String
But you do have to escape quotation marks
String blanks = "\t\t\t\t\n";
String quote = "He said, \"Attack!\"";
Operations on String values
Concatenation
The only operator that we will use directly with String values is the + (concatenation) operator
This operator creates a new String that is the concatenation of the two source Strings
As with numerical types, the + operator does not change the two Strings being concatenatedString word;
word = "tick" + "tock"; // word is "ticktock"
Concatenation with other types
Concatenation is a great tool for merging lots of different types into a String
Confusion can arise:
String word;word = 99 + " problems"; // word is
// "99 problems"
String word;word = "love potion #" + 4 + 5; // word is "love potion #45"word = "love potion #" + (4 + 5); // word is "love potion #9"
Strings are objects
Objects have data inside of them but also have the ability to do things with methods
Among other things, a String can: Compare itself with other Strings Find its length Say which character is located at
position i Generate a substring
String comparison
To see if two Strings are identical, use the equals() method:
If they are the same (including case), the method will return true
If they are not, the method will return false
String word1 = "lettuce";String word2 = "let us";boolean same = word1.equals ( word2 ); // false
String comparison
To see which String goes first in the dictionary, use the compareTo() method:
If word1 comes first, value will be a negative number
If word2 comes first, value will be a positive number
If they are the same, value will be 0
String word1 = "hard work";String word2 = "success";int value = word1.compareTo( word2 ); // < 0
String length
To find the length of a String, use the length() method:
It is possible to have a String of length 0:
String word = "a mile long";int length = word.length(); // length = 11
String nothing = "";int length = nothing.length(); // length = 0
char at position i
To find the char at position i in a String, use the charAt() method:
Woe betide the man (or woman) who asks for a character out of range:
String word = "walnut";char c = word.charAt(3); // c = 'n'
String word = "short";char c = word.charAt(10); // ouch!
Getting a substring
To get a substring of a String, use the substring() method:
The first int tells which char to start on, the second int says which char to stop before
String word1 = "disco fever";String word2 = word1.substring(3,7);
//word2 = "co f"
Example
Write a program that reads a first and a last name
Then, output only the person's initials
Wrapper Classes
Classes and objects are useful
There are certain things that are difficult to do with the operations we've shown you
For example, how do you turn a String representation of a number like "847" into the actual int 847?
Wrapper classes!
Wrapper classes
Each primitive data type in Java has a wrapper class
We will focus on 3: Integer Double Character
Integer class
The main uses of the Integer class are converting ints to and from Strings
To convert a String to an int, use the parseInt() method
To convert an int to a String, use the toString() method (or just concatenate)
String number = "345";int value = Integer.parseInt(number);
int value = 543;String number = Integer.toString(value);
Double class
The Double class is much like the Integer class
To convert a String to a double, use the parseDouble() method
To convert a double to a String, use the toString() method (or just concatenate)
String number = "-0.4581";double value = Double.parseDouble(number);
double value = 6.02e23;String number = Double.toString(value);
Character class
The Character class is mostly useful for getting information about a particular char
For example, you can find out whether a char is a digit, is a letter, is uppercase, or is lowercase by calling the isDigit(), isLetter(), isUpperCase(), or isLowerCase() methods, respectively
char c = '8';boolean value = Character.isDigit(c); //true
Quiz
Upcoming
Next time…
Introduction to if-statements Lab 3
Reminders
Keep reading Chapter 3 of the textbook
Keep working on Project 1 Due next Friday