Ap Java Blue Pelican Ch.1-11
Negation (not) operator
Another operator we need to know about is the not operator (!). It is officially called the negation operator. What does it mean if we say not true (!true)? ... false, of course. 1. System.out.println(!true); //false 2. System.out.println(!false); //true 3. System.out.println( !(3 < 5) ); //false 4. System.out.println( !(1 = = 0) ); //true
Signature of a method
Below we will give the description of some methods of the Math class... along with the signatures of the method. First, however, let's explain the meaning of signature (also called a method declaration). Consider the signature of the sqrt( ) method: double sqrt( double x ) | | | type returned | | method name | type of parameter we send to the method
Braces
Braces are not needed if only one line of code is in the if or else parts. Likewise, the absence of braces implies only one line of code in if or else parts.
Operator precedence
Consider a problem like: System.out.println( (true && false) | | ( (true && true) | | false ) ); 8-2 We can tell what parts we should do first because of the grouping by parenthesis. However, what if we had a different problem like this? System.out.println( false && true || true); Which part should we do first? The answers are different for the two different ways it could be done. There is a precedence (order) for the operators we are studying in this lesson (see Appendix H for a complete listing of operator precedence). The order is: ! = = != && ||
Creation of booleans
Create boolean variables as shown in the following two examples: boolean b = true; boolean z = ( (p < j) && (x != c) ); boolean b = true, c = false;
The if statement
Example 1: //Get a grade from the keyboard Scanner kbReader = new Scanner(System.in); System.out.print("What is your grade? "); int myGrade = kbReader.nextInt( ); //Make a decision based on the value of the grade you entered if (myGrade >= 70) { //Execute code here if the test above is true System.out.println("Congratulations, you passed."); } else { //Execute code here if the test above is false System.out.println("Better luck next time."); }
public static void main(String args[]) { System.out.println("Hello world"); System.out.println("Hello Again"); }
Hello World Hello Again
Loop
However, this only works if we repeatedly execute this line of code, ...first with j = 3, then with j = 4, j = 5, ...and finally with j = 79. The full structure of the for-loop that will do this is: int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop. } System.out.println("The final sum is " + sum); // prints 3157
The break command
If the keyword break is executed inside a for-loop, the loop is immediately exited (regardless of the control statement). Execution continues with the statement immediately following the closing brace of the for-loop.
Braces
If there is only one line of code or just one basic structure (an if-structure or another loop) inside a loop, then the braces are unnecessary. In this case it is still correct (and highly recommended) to still have the braces...but you can leave them off. for (j = 3; j <= 79; j++) is equivalent to for (j = 3; j <= 79; j++) sum=sum+j; { sum=sum+j;}
Multiple inputs
In a similar way nextInt( ) and nextDouble( ) can be used multiple times to parse data input from the keyboard. For example, if 34 88 192 18 is input from the keyboard, then nextInt( ) can be applied four times to access these four integers separated by white space.
Correct Syntax
In the above examples there are three things we must change in order to have correct Java syntax: 1. To compare two quantities...such as (y = 97) above we must instead do it this way: (y = = 97)....recall that a single "=" is the assignment operator. Similarly, read y != 97 as "y is not equal to 97". 2. In Java we don't use the word "and" to indicate an AND operation as above. We use "&&" instead........( (x <10) && (y = = 97) ) 3. In Java we don't use the word "or" to indicate an OR operation as above. We use "||" instead........( (x <10) | | (y = = 97) )
Mysterious objects
In the above three examples we used the following code: Scanner kbReader = new Scanner(System.in); It simply creates the keyboard reader object (we arbitrarily named it kbReader) that provides access to the nextInt( ), nextDouble( ), next( ), and nextLine( ) methods. For now just accept the necessity of all this...it will all be explained later.
Inputting an entire line of text
Inputting a String (it could contain spaces) from the keyboard using nextLine( ): import java.io.*; import java.util.*; public class Tester { public static void main( String args[] ) { Scanner kbReader = new Scanner(System.in); System.out.print("Enter your String here. "); //Enter One Two String s= kbReader.nextLine( ); System.out.println( "This is my string,... " + s); } }
An anomaly
It is not permissible to follow nextInt( ) or nextDouble( ) with nextLine( ). If it is necessary to do this, then a new Scanner object must be constructed for use with nextLine( ) and any subsequent inputs.
When the loop finishes
It is often useful to know what the loop variable is after the loop finishes: 11-2 for (j = 3; j <= 79; j++) { . . . some code . . . } System.out.println(j); //80 On the last iteration of the loop, j increments up to 80 and this is when the control statement j <= 79 finally is false. Thus, the loop is exited.
Multiple declarations
It is possible to declare several variables on one line: double d, mud, puma; //the variables are only declared double x = 31.2, m = 37.09, zu, p = 43.917; //x, m, & p declared and initialized // zu is just declared
Declaring the loop variable
It is possible to declare the loop variable in the initializing portion of the parenthesis of a for-loop as follows: for (int j = 3; j <= 79; j++) { .. . } In this case the scope of j is confined to the interior of the loop. If we write j in statement outside the loop (without redeclaring it to be an int), it won't compile. The same is true of any other variable declared inside the loop. Its scope is limited to the interior of the loop and is not recognized outside the loop as is illustrated in the following code: for (j = 3; j <= 79; j++) { double d = 102.34; .. . } System.out.println(d); //won't compile because of this line
Leave off the else
Scanner kbReader = new Scanner(System.in); System.out.print("What state do you live in? "); String state = kbReader.nextLine( ); //get state from keyboard System.out.print("What is the price? "); double purchasePrice = kbReader.nextDouble( ); //get price from keyboard double tax = 0; if ( (state = = "Texas") || (state = = "Tx") ) { //Execute code here if test above is true tax = purchasePrice *.08; //8% tax } double totalPrice = purchasePrice + tax; System.out.println("The total price is " + totalPrice + ".");
Else if
Scanner kbReader = new Scanner(System.in); System.out.println("What is your grade? "); int theGrade = kbReader.nextInt( ); if (theGrade>=90) { System.out.println("You made an A."); } else if (theGrade>=80) { System.out.println("You made a B."); } else if (theGrade>=70) { System.out.println("You made a C."); } else if (theGrade>=60) { System.out.println("You made a D."); } else { System.out.println("Sorry, you failed."); }
toLowerCase
String bismark = "Dude, where's MY car?"; System.out.println( bismark.toLowerCase( ) ); // prints dude, where's my car?
Concatenation
String mm = "Hello"; String nx = "good buddy"; String c = mm + nx; System.out.println(c); //prints Hellogood buddy...notice no space between o & g //space if + " " added
A more useful form of substring
String myPet = "Sparky the dog"; String smallPart = myPet.substring(4, 12); System.out.println(smallPart); //prints ky the d
The length method
String theName = "Donald Duck"; int len = theName.length( ); System.out.println(len); //prints 11...notice the space gets counted
Loop
Suppose we want to sum up all the integers from 3 to 79. One of the statements that will help us do this is: sum = sum + j;
toUpperCase
System.out.println( "Dude, where's My car?".toUpperCase( ) ); //prints DUDE, WHERE'S MY CAR?
Main Method
System.out.println("Hello World!");
Escape sequences
System.out.println("Path = c:\\nerd_file.doc"); Prints the following: Path = c:\nerd_file.doc System.out.println("Name:\t\tAddress:"); Prints the following: Name: Address:
PEMDAS
System.out.println(5 + 3 * 4 -7); //10 System.out.println(8 - 5*6 / 3 + (5 -6) * 3); //-5
int count =15; count = count + 3;
System.out.println(count); //18 //this is illegal in algebra; however, in computer science it //means the new count equals the old count + 3.
The assignment operator
The assignment operator is the standard equal sign (=) and is used to "assign" a value to a variable. int i = 3; // Ok,...assign the value 3 to i. Notice the direction of data flow 3 = i; // Illegal! Data never flows this way! double p; double j = 47.2; p=j; //assign the value of j to p.Both p and j are now equal to 47.2
Fundamental arithmetic operations
The basic arithmetic operation are +, -, * (multiplication), / (division), and % (modulus). System.out.println(5%3); will print 2.
Error
There is just one difficulty with the above code in Example 2. It won't work! The problem is with how we are trying to compare two Strings. It cannot be as follows: state = = "Texas" Rather, we must do it this way: state.equals("Texas") A good way to cover all the bases in the event someone mixes upper and lower case on the input is as follows: ( state.equalsIgnoreCase("Texas") | | state.equalsIgnoreCase("Tx") )
Inputting a double
Use the nextDouble method to input a double from the keyboard: import java.io.*; import java.util.*; public class Tester { public static void main( String args[] ) { } } Scanner kbReader = new Scanner(System.in); System.out.print("Enter your decimal number here. "); //1000.5 double d = kbReader.nextDouble( ); System.out.println( 3 * d ); //prints 3001.5
Inputting an integer
Use the nextInt method to input an integer from the keyboard: import java.io.*; //see "Imports necessary" on next page import java.util.*; public class Tester { public static void main( String args[] ) { Scanner kbReader = new Scanner(System.in); //see "Mysterious //objects" on next page System.out.print("Enter your integer here. "); //enter 3001 int i = kbReader.nextInt( ); System.out.println(3 * i); //prints 9003 }
Rules for naming
Variable names must begin with a letter (or an underscore character) and cannot contain spaces. The only "punctuation" character permissible inside the name is the underscore ("_"). Variable names cannot be one of the reserved words that are part of the Java language.
Double
Variable type .used to store "floating point" numbers (decimal fractions). double means "double precision". Sample code: public static void main(String args[]) { double d = -137.8036; System.out.println(d); d = 1.45667E23; //Scientific notation...means 1.45667 X 1023 }
Int
Variable type used to store integers (positive or negative) Sample code: public static void main(String args[]) { int age = 59; System.out.println(age); }
String
Variable type used to store things in quotes....like "Hello world" Sample code: public static void main(String args[]) { String s = "Hello cruel world"; System.out.println(s); }
Imports necessary
We must import two classes,....java.io.* and java.util.* that provide methods for inputting integers, doubles, and Strings. See Appendix I for more on the meaning of "importing".
Escape sequences
What "is" the right way? String s = "What \"is\" the right way?"; System.out.println(s); //prints What "is" the right way? String s = "Here is one line\nand here is another."; System.out.println(s); Prints the following: Here is one line and here is another. String s = "Here is one line\nand here is another."; System.out.println(s); Prints the following: Here is one line and here is another. String s = "Here is one line\nand here is another."; System.out.println(s); Prints the following: Here is one line and here is another.
Integer division truncation
When dividing two integers, the fractional part is truncated (thrown away) as illustrated by the following: int x = 5; int y = 2; System.out.println(x / y); //Both x and y are integers so the "real" answer of 2.5 //has the fractional part thrown away to give 2
Truth tables
a &&b false && false=false false&&true=false true&&false=false true&&true=true a||b false||false= false false||true=true true||false=true true||true=true
Naming conventions for variables
bigValue big_value
Inputting a string
import java.io.*; import java.util.*; public class Tester{ public static void main( String args[] ) { } } Scanner kbReader = new Scanner(System.in); System.out.print("Enter your String here. "); //Enter One Two String s = kbReader.next( ); //inputs up to first white space System.out.println( "This is the first part of the String,... " + s); s = kbReader.next( ); System.out.println( "This is the next part of the String,... " + s);
A piece of a String (substring)
we can pick out a piece of a String...substring String myPet = "Sparky the dog"; String smallPart = myPet.substring(4); System.out.println(smallPart); //prints ky the dog
Truth
x++ increments x after it is used in the statement. ++x increments x before it is used in the statement. x-- decrements x after it is used in the statement. --x decrements x before it is used in the statement. int q = 78; int p = 2 + q++; System.out.println("p = " + p + ", q = " + q); //p = 80, q = 79 int q = 78; int p = ++q + 2; System.out.println("p = " + p + ", q = " + q); //p = 81, q = 79
Increment and Decrement
x++; means the same as x--; meansthesameas x++ is the same as ++x x-- is the same as --x int y = 3; y++; System.out.println(y); //4 x = x +1; x=x-1; (the ++ can be on either side of x) (the -- can be on either side of x)
Nested loops
"Nested loops" is the term used when one loop is placed inside another as in the following example: for(int j = 0; j < 5; j++) { System.out.println("Outer loop"); // executes 5 times for(int k = 0; k < 8; k++) { System.out.println("...Inner loop"); // executes 40 times } } The inner loop iterates eight times for each of the five iterations of the outer loop. Therefore, the code inside the inner loop will execute 40 times.
Boolean
( (x <10) AND (y = 97) ) Both parts are true so the whole thing is true. ( (x <10) AND (y = -3) ) First part is true, second part is false, whole thing false ( (x <10) OR (y = 97) ) If either part is true (both are) the whole thing is true. ( (x <10) OR (y = -3) ) If either part is true (first part is) the whole thing true.
Block rems
/* ................ */
Warning
A very common mistake is to put a semicolon immediately after the parenthesis of a for- loop as is illustrated by the following code: for (j =3; j <= 79; j++); { //This block of code is only executed once because of the inappropriately //placed semicolon above. . . . some code . . . }
Methods, signature, description
see blue pelican
System.out.println( )
completes printing on the current line and pulls the print position down to the next line where any subsequent printing continues.
Casting
double d = 29.78; int i = d; //won't compile since i is an integer and it would have to chop-off // the .78 and store just 29 in i....thus, it would lose information. There is a way to make the above code work. We can force compilation and therefore result in 29.78 being "stored" in i as follows (actually, just 29 is stored since i can only hold integers): int i = (int)d; //(int) "casts" d as an integer... It converts d to integer form.
Declaring and initializing
double x; //this declares x to be of type double x = 1.6; //this initializes x to a value of 1.6
Constants
final double PI = 3.14159; The following illustrates that constants can't be changed: final double PI = 3.14159; PI = 3.7789; //illegal final String NAME= "Peewee Herman"; final int LUNCH_COUNT = 122;
The most precise
int i = 4; double d = 3; double ans = i/d; //ans will be 1.33333333333333...the result is double precision 20 + 5 * 6.0 returns a double. The 6.0 might look like an integer to us, but because it's written with a decimal point, it is considered to be a floating point number...a double.
Concatenating a String and a numeric
int x = 27; String s = "Was haben wir gemacht?"; //German for "What have we done?" String combo = s + " " + x; System.out.println(combo); //prints Was haben wir gemacht? 27
Control expression
j <= 79 We continue looping as long as this boolean expression is true. In general this expression can be any boolean expression. For example, it could be: count = = 3 s + 1 < alphB s > m +19 etc.
Initializing expression
j = 3 If we had wanted to start summing at 19, this part would have read, j = 19.
Step expression
j++ This tells us how our variable changes as we proceed through the loop. In this case we are incrementing j each time; however, other possibilities are: j-- j=j+4 j=j*3 etc.
System.out.print( )
prints on the current line and stops there. Any subsequent printing continues from that point.
Hello World
public class Tester //We could put any name here besides Tester { public static void main(String args[]) System.out.println("Hello World!"); { } }
Skeleton
public class Tester { public static void main(String args[]) { } }
indices
the various characters in a String are numbered starting on the left with 0
