cop 2210 final review - francisco r....
TRANSCRIPT
COP 2210 Final Review
By Francisco R. Ortega
Disclaimer
• This is not intended to be a full or official review.
• You are responsible to study and know all the materials
• This cannot replace missed lectures or labs
• Study yours notes , labs, homework and online notes provided to you.
• If information here is beyond the scope of class, ignore it.
Working with Classes
• Create an object
– MyClass C = new MyClass(20);
• Call a method
– Int myValue = C.GetValue();
– C.Setvalue(10);
Create a ClassClass MyClass { //beginning of class declaration
private int value=0; // Instance Variable
MyClass(int value) { //constructor
this.value = value;
}
int getValue() { // Accessor/Getter Method
return this.value;
}
void setValue(int value){ // Mutator/Setter Method
this.value = value
}
}//end of class
Math Operators
Operator
Meaning
Precedence
* , / , %
Multiplication, Division,
Integer ModulusHighest
+ , -
Addition, Subtraction,
Unary Positive and NegativeLowest
Overloading Constructors/Methods
public BankAccount (String acctNum, doubleinitialBalance){
accountNumber = acctNum ;
balance = initialBalance ;
}
public BankAccount(String acctNum){
accountNumber = acctNum ;
balance = 0 ;
}
Integer Division / Mod
Integer Division
Examples: 10 / 4 = 2 9 / 5 = 1 99 / 100 = 0
Unknowingly dividing one integer by another and expecting a “real” result is an extremely common source of logic errors!!!
Integer Mod
Examples: 10 % 4 = 2 9 % 5 = 4 99 % 100 = 99
For both integer division and modulus, the right-hand operand must be non-zero. Otherwise, the Arithmetic Exception “/ by zero” will be thrown.
Math Function
NameNumber of
ArgumentsArgument Type Type Returned Returns
sqrt 1 int or double doubleThe nonnegative square root
of the argument
abs 1 int or double same as the argumentThe absolute value (“distance
from zero”) of the argument
min 2 int or double same as the argumentThe lesser of the
two arguments
max 2 int or double same as the argumentThe greater of the
two arguments
pow 2 int or double doubleThe first argument raised to
the power of the second
round 1 double longThe argument rounded to the
nearest integer, as a long
Math Functions
• double v1 = 10.0;
• double v2 = 2.0;
• double v3 = 3.6;
• double v4 = -3.6;
• double s = Math.sqrt(v2);
• double p = Math.pow(v1, v2);
• double a = Math.abs(v2 - v1);
• double r = Math.round(v3);
• double m1 = Math.max(v1, v2);
• double m2 = Math.min(v3, v4);
JOptionPane
String input =
JOptionPane.showInputDialog(null,"What is the
amount due?", “AMOUT DUE
TITLE",JOptionPane.QUESTION_MESSAGE) ;
Double inputValue = Double.parseDouble(input);
JOptionPane.showMessageDialog(null, “The amout
due is” + inputValue);
Decision Making(Selection or Conditional Execution)
Relational Operators
Algebra Java Meaning
< < less than
≤ <= less than or equal to
> > greater than
≥≥≥≥ >= greater than or equal to
= == equals
≠≠≠≠ != does not equal
Relational Operators and Expressions
Example:
Math.pow(b,2) – 4 * a * c < 0
IF STATMENTS
if (a == “10”)
runMyApp1();
else if (a == “20”)
runMyApp2();
else
runMyApp3();
if (a == “10”)
{
runMyApp1();
}
Else
{
runMyApp2();
}
Nested if statements!
if (a == 10 && a == b)
{
c = a +b;
d = 1;
if (c == 30)
d = 0;
}
if (a == 10)
{
//do something
if (a == b)
{
// do something else
}
}
Truth Tables
A B !B A && B A || B
0 0 1 0 0
0 1 0 0 1
1 0 1 0 1
1 1 0 1 1
Operator Presedence
!highest
*, /, %, +, -
>, >=, <, <=, ==, !=
&&
||lowest
• It is not necessary to enclose relational expressions in parentheses when they are joined by && or ||– relationals have higher precedence than these
operators
– a && b && c is the same as a && (b && c)
• Since ! has the highest precedence of all, it isnecessary to use parentheses – !a > b is not the same as !(a > b)
• It is probably a good idea to always use parentheses with boolean expressions
Operators…
IterationRepetitions or Looping
While and Do While
while (boolean expression)
{
statement(s)
}
do
{
statement(s)
}
while (boolean expression) ;
FOR LOOP
for (initialization action ; boolean expression ; update action)
{
statements ;
}
for (int i=0 ; i < 20 ; i++)
{
statements ;
}
for (int i=0,j=0; i < 10;i++,j+=i + 2)
System.out.println("i:" + i + ";j:" + j);
Know your scanner!import java.util.Scanner ;
Scanner scan = new Scanner(new file(“a.txt”) ;
While (scan.hasNext())
{
//say file is Name age .For example(Frank 35)
Scanner scan2 = new Scanner(scan.next());
String n = scan2.next();
int age = scan2.nextInt();
}
Random Numbers
Random r= new Random() ;
double d 1 = r.nextDouble();//assigns some random double value to x such that 0.0 <= x < 1.0
int num = generator.nextInt()
int num = generator.nextInt(50) // 0 to n-1
Random Numbers
• range a..b (inclusive)
– nextInt( b – a + 1 ) + a
• NUMBER between 10 to 99
– Either:
• nextInt( 99 – 10 + 1 ) + 10
• nextInt( 90 ) + 10
Random Numbers Common Errors
for (int i = 1 ; i <= 10 ; i++)
{
Random r = new Random() ;
int randNum = r. nextInt() ;
System.out.println(randNum) ;
}
How do we fix it?
Wrapper Classes
Primitive Type Wrapper Class
double Double
int Integer
boolean Boolean
char Character
ArrayList<Integer> list = new ArrayList<Integer>() ;
ArrayList Operations
• ArrayList<TYPE> myList = new ArrayList<TYPE>();
• TYPE a = list.get(index);
• list.add(a); //add object to list.
• list.set(index,a); //changes object a in pos index.
• list.add(index,a); //add object a at pos index & shift
• list.remove(index); //deletes object @ specific index.
• list.clear(); //removes all
• list.size(); // finds size of list.
• list.isEmpty(); // true or false depending if list empty
Files
• Reading a file into a scanner
– Scanner fileIn = new Scanner( new File ( “Votes.in”) );
• Writing to a file
– Example 1:
• PrintWriter outFile = new PrintWriter("Output.txt") ;
– Example 2:• File outputFile = new File("results.txt")
• PrintWriter out = new PrintWriter(outputFile) ;
• Close a file
– outfile.close() ;
Files: OUTPUT
PrintWritter pw = new PrintWritter(“o.txt”);
pw.println(“First Line”);
pw.print(“second”);
pw.print(“ line”);
pw.println(“third line”);
pw.close();
Designing Classes
• Read UNIT 10 and bring questions for Thursday
and Review this weekend.
• Remember that java passes all parameters by
VALUE (COPY)
– Also remember, that the variable that holds your
objects is just a memory reference.
• Therefore, you can modify the object you pass.
• Ask Frank Hernandez about review this weekend
– His email is [email protected]
Has-A vs is-A
• Has-A / Aggregation / Composition
– Dealer has a Car
– PokerHand has a Card
• Is-a / Inheritance
– A Student is a Person
– A TexasHoldemPoker is a PokerGame
• Helper Classes
– Card.ShowCard() helps Hand.ShowHand()
Static!!!! STATIC !!!
• Static variable: – private static int howMany= 0 ;
• Using the static within the constructor:– public CarDealer(String name)
{//some codehowMany++; }
• Static functions:– public static int getHistoricalCarCountInDealer()
{
return howMany;
}
STRINGS!
• String magic = “Abracadabra!”
• int pos = magic.indexOf("A") ; // pos gets 0
• pos = magic.indexOf("Abra") ; // 0 again
• pos = magic.indexOf("abra") ; // pos gets 7
• pos = magic.indexOf('b') ; // pos gets 1
• pos = magic.indexOf(magic) ;// 0 WHY?
• pos = magic.indexOf(“XYZ”); // -1 WHY?
• pos = magic.indexOf(‘a’,4); //pos gets 5
– (the 5th character),
String
• String magic = "Abracadabra!" ;
• String sub = magic.substring(0,4) ; // sub gets "Abra"
• sub = magic.substring(0,1) ; // "A"
• sub = magic.substring(4,7) ; // "cad"
• sub = magic.substring(0,magic.length()) ;
• String word = "ada" ;
• sub = magic.substring(magic.indexOf(word),11) ;
More about Strings
• StringIndexOutOfBoundsException
• string-object.toUpperCase()
• string-object.toLowerCase()
• string-object.charAt(index)
• STRINGS ARE IMMUTABLE
• If myString.equals(“Francisco”)
– You cannot do ==
• If myString.equalsIgnoreCase(“francisco”)
SOLVE
String s1 = new String("abcdef");
String s2 = new String("123abc");
What are the values of the following expressions?
a. s1.substring(3)
b. s1.substring(1,4)
c. s1.charAt(0) == s2.charAt(3)
d. s1.substring(0,3).equals(s2.substring(4))
String / CompareTo Method
• int a = s1.compareTo(s2)
• a is negative if s1 is less than s2
• a is zero if s1 is equal to s2
• a is positive if s1 is greater than s2
• Strings are compare as they would appear in the dictionary
• If (s1.compareTo(s2) > 0) …
• Also you can use compareToIgnoreCase
String – compareTo… HOW?
Review Questions from Book
• The following questions come from Edition 3.
They may be similar to your current edition
Chapter 5
Chapter 5
Chapter 5
Chapter 5
Chapter 5
Chapter 6
Chapter 6
Chapter 7
Chapter 8
Chapter 8
Questions
• Study hard…. GOOD LUCK!