p. 1
blue pelican java by charles e cook version 3.0.5e copyright © 2004 2007 by charles e cook refugio tx all rights reserved
[close]
p. 3
1 peter piper picked a peck of pickled peppers 2 i like computer science 1-1 lesson 1 hello world program skeleton enter the following program skeleton compile prepare it to run and then run execute your instructor may have you give it a specific project name otherwise call the project lesson1 if you do not know how to enter and execute a program ask your instructor or use the appendices in this book for two of the more popular programming environments see appendix n for the bluej environment and appendix o for the jcreator environment public class tester public static void mainstring args at this point don t worry about what any of this means it s just something we must do every time soon we will learn the meaning of all of this for now it s just the skeleton that we need for a program adding some meaningful code now let s add some meaningful code inside the main method notice this word method we will constantly refer to methods throughout this course we will also add a remark public class tester we could put any name here besides tester public static void mainstring args system.out.println hello world remarks notice the rem remark above that starts with you can put remarks anywhere in the program without it affecting program operation remarks are also called comments or notes printing system.out.println hello world is how we get the computer to printout something notice the trailing semicolon most lines of code are required to end in a semicolon now try putting in some other things in the println parenthesis above each time recompile and run the program:
[close]
p. 4
1-2 3 25/5 4 4 7.0445902 5 13 159.56 two printlns for the price of one next modify your program so that the main method looks as follows public static void mainstring args system.out.println hello world system.out.println hello again run this and note that it prints hello world hello again printing sideways now remove the ln from the first println as follows public static void mainstring args system.out.print hello world system.out.println hello again run this and note that it prints hello worldhello again here are the rules concerning println and print · system.out.println completes printing on the current line and pulls the print position down to the next line where any subsequent printing continues · system.out.print prints on the current line and stops there any subsequent printing continues from that point an in-depth look at rems let s take a further look at rems consider the following program class in which we wish to document ourselves as the programmer the date of creation and our school public class tester programmer kosmo kramer date created sept 34 1492 school charles manson high school berkley ca public static void mainstring args system.out.println hello again }
[close]
p. 5
1-3 block rems it can get a little tedious putting the double slash rem-indicator in front of each line especially if we have quite a few remark lines in this case we can block rem all the comment lines as follows public class tester programmer kosmo kramer date created sept 34 1492 school charles manson junior high berkley ca public static void mainstring args system.out.println hello again notice we use to indicate the start of the block and for the end everything between these two symbols is considered to be a remark and will be ignored by the computer when compiling and running project from me to you create a new package in the lesson 1 project called frommetoyou with the following content also include remarks above public class frommetoyou that identifies you as the author along with the date of creation of this program author your name date created september 2010 public class frommetoyou public static void mainstring args supply code in the place of that will produce the following printout from your name address dell computer bldg 13 date september 2010 to ms bement message help i m trapped inside a computer complete projects0201 and project0202 on p 54 of fundamentals of java.
[close]
p. 6
2-1 lesson 2 variable types string int double three variable types a good way to learn the following points is to modify the code of the hello world program according to the suggestions below 1 string used to store things in quotes like hello world sample code public static void mainstring args string s hello cruel world system.out.printlns 2 int used to store integers positive or negative sample code public static void mainstring args int age 59 system.out.printlnage 3 double used to store floating point numbers decimal fractions double means double precision sample code public static void mainstring args double d -137.8036 system.out.printlnd d 1.45667e23 scientific notation means 1.45667 x 10 declaring and initializing when we say something like double x 1.6 we are really doing two things at once we are declaring x to be of type double and we are initializing x to the value of 1.6 all this can also be done in two lines of code as shown below instead of one if desired double x this declares x to be of type double x 1.6 this initializes x to a value of 1.6 what s legal and what s not int arws 47.4 illegal won t compile since a decimal number cannot fit into an integer variable double d 103 legal same as saying the decimal number 103.0 23
[close]
p. 7
2-2 rules for variable names 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 key words see appendix a that are part of the java language legal names agro d d31 hoppergee hopper_gee largearea goldnugget illegal names 139 139abc fast one class slow.sally double gold;nugget hopper-gee variable naming conventions it is traditional although not a hard and fast rule for variable names to start with a lower case letter if a variable name consists of multiple words combine them in one of two ways bigvalue jam everything together first word begins with a small letter and subsequent words begin with a capital big_value separate words with an underscore declaring several variables in a single declaration and simultaneously assigning them initial values sample code public static void mainstring args int x,y,z=7 x=25 y=8 system.out.printlnx system.out.printlny system.out.printlnz }
[close]
p. 8
2-3 exercise on lesson 2 name 1 what are the three main types of variables used in java and what are they used to store 2 what type of variable would you use to store your name 3 what type of variable would you use to store the square root of 2 4 what type of variable would you use to store your age 5 write a single line of code that will create a double precision variable called p and store 1.921 x 10 -16 in it 6 write a single line of code that will create an integer variable called i and store 407 in it 7 write a single line of code that will create a string variable called my_name and store your name in it 8 write a line of code that will declare the variable count to be of type int don t initialize 9 write a line of code that initializes the double precision variable bankbalance to 136.05 assume this variable has already been declared 10 which of the following are legal variable names scooter13 139_scooter homer-5 ;mary public doubled double ab c 11 which of the following is the most acceptable way of naming a variable multiple answers are possible a groovydude b groovydude c groovydude d groovydude e groovy_dude f groovydude 12 comment on the legality of the following two lines of code double dist 1003 int alt 1493.86;
[close]
p. 9
2-4 13 write and execute a program in the lesson2 package with the class name variable to declare a double variable called payrate and simultaneously initialize it to 35.87 declare three integer variables a,b,c in a single declaration and simultaneously initialize b to 4 assign a the value 22 c the value 88 your output should look similar to the following 35.87 22 4 88 14 write and execute a program in the lesson2 package with the class name holiday that prints your name and four of your favorite holidays you celebrate along with the month in which they are celebrated in print out a copy of your code and the program after it has been run your output should look similar to the following however you will need to supply the appropriate holiday and month use string variables and then print the strings favorite holidays for your name include the following thanksgiving in november memorial day in may christmas in december labor day in september
[close]
p. 10
3-1 lesson 3 simple string operations in this lesson we will learn just a few of the things we can do with strings concatenation first and foremost is concatenation we use the plus sign to do this for example string mm hello string nx good buddy string c mm nx system.out.printlnc prints hellogood buddy notice no space between o g the above code could also have been done in the following way string mm hello string nx good buddy system.out.printlnmm nx prints hello good buddy notice the space we could also do it this way system.out.println hello good buddy prints hello good buddy the length method use the length method to find the number of characters in a string string thename donald duck int len thename.length system.out.printlnlen prints 11 notice the space gets counted right now we don t see much value in this length thing just wait a piece of a string substring we can pick out a piece of a string substring string mypet sparky the dog string smallpart mypet.substring4 system.out.printlnsmallpart prints ky the dog why do we get this result the various characters in a string are numbered starting on the left with 0 these numbers are called indices notice the spaces are numbered too spa rky th edog 0 1 2 3 4 5 6 7 8 9 10 11 12 13 a more useful form of substring but wait there s another way to use substring string mypet sparky the dog string smallpart mypet.substring4 12 system.out.printlnsmallpart prints ky the d th how do we get ky the d start at k the 4 index as before go out to the 12 th index o in this case and pull back one notch that means the last letter is d so now we see that the k has index 4 and we go from k all the way to the end of the string to get ky the dog
[close]
p. 11
3-2 conversion between lower and upper case tolowercase converts all characters to lower case small letters string bismark dude where s my car system.out.println bismark.tolowercase prints dude where s my car touppercase converts all characters to upper case capital letters system.out.println dude where s my car touppercase prints dude where s my car note length substring tolowercase and touppercase are all methods of the string class there are other methods we will learn later concatenating a string and a numeric it is possible to concatenate a string with a numeric variable as follows int x 27 string s was haben wir gemacht german for what have we done string combo s x system.out.printlncombo prints was haben wir gemacht 27 escape sequences how do we force a quote character to printout or to be part of a string use the escape sequence to print the following note escape sequences always start with the character see appendix b for more on escape sequences what is the right way string s what is the right way system.out.printlns prints what is the right way another escape sequence n will create a new line also called line break as shown below string s here is one line nand here is another system.out.printlns prints the following here is one line and here is another the escape sequence will allow us to print a backslash within our string otherwise if we try to insert just a single it will be interpreted as the beginning of an escape sequence system.out.println path c nerd_file.doc prints the following path c nerd_file.doc the escape sequence t will allow us to tab over the following code tabs twice system.out.println name t taddress prints the following name address:
[close]
p. 12
3-3 exercise on lesson 3 name 1 write code in which a string variable s contains the number of rabbits is an integer variable argh has a value of 129 concatenate these variables into a string called report then print report the printout should yield the number of rabbits is 129 note that we want a period to print after the 9 2 what is the output of system.out.println p.touppercase if p groovy dude 3 write code that will assign the value of computer science is for nerds to the string variable g then have it print this string with nothing but small letters 4 what will be the value of c string c string m the gettysburg address c m.substring4 5 what will be the value c string b four score and seven years ago c b.substring7 12 6 what is the value of count int count string s surface tension count s.length 7 write code that will look at the number of characters in string m look here and then print look here has 10 characters use the length method to print the 10 you must also force the two quotes to print 8 how would you print the following all good men should come to the aid of their country 9 write code that will produce the following printout using only a single println hello hello again 10 write code that will produce the following printout a backslash looks like this right?
[close]
p. 13
11 what is output by the following string pq eddie haskel int hm pq.length string ed pq.substringhm 4 system.out.printlned 12 which character is at the 5 index in the string herman munster 3-4 13 write and execute a programthin the lesson3 package with the class name salesdata that declares and assigns the following variables and prints them as shown below tax rate of .0675 number of items of 15 total sale of 122.98 price per item of 2.45 items in stock of 100 and average items sold of 3.4987302 you need to assign each value and string a variable and use concatenation to print the output the output should resemble the following tax rate .0675 number of items 15 total sales $122.98 price per item $2.45 items in sock 100 average items sold 3.4987302 14 write and execute a program in the lesson3 package with the class name schedule using concatenation between the name of the hour and the class your output should resemble the output below schedule for your name first hour your first hour class room number second hour computer programming i b210 third hour your third hour class room number fourth hour your fourth hour class room number 15 write and execute a program in the lesson3 package with the class name length use the length method to find the number of characters in the string today we are learning hour to write a variety of strings in java 16 write and execute a program in the lesson3 package with the class name surprise use the substring to print the following indices 5 24 the value of the string is you better get ready for some turkey and pumpkin pie later this month 17 write and execute a program in the lesson3 package with the class name upandlower use the conversion between lower and upper case commands to change the sentence to be or not to be that is the question to upper case letters and the sentence a quarter is 25 cents to lower case letters 18 write and execute a program in the lesson3 package with the class name school use concatenating a string and number to produce the following output this program will tell you a little about anoka high school terms per year 4 classes per term 4 minutes per class period 85 credits per year 16
[close]
p. 14
18 write and execute a program in the lesson3 package with the class name train use the escape sequence to force a quote and create a new line the output should look like the following as the train left the station the conductor yelled all aboard project name that celebrity 19 write and execute a program in the lesson3 package with the class name namethatcelebrity in which only partially recognizable names of celebrities are to be produced in a real implementation of this game the idea is for a contestant to be able to guess the real name of the celebrity after the first two and last three letters are dropped from the name we have been given the task of testing the feasibility of this idea by producing the following printout allan alda lan a john wayne hn wa gregory peck egory p begin your code within the main method as follows string s1 allan alda string s2 john wayne string s3 gregory peck apply the length and substring methods to these strings to produce the above printout.
[close]
p. 15
4-1 lesson 4 using numeric variables 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 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 fundamental arithmetic operations the basic arithmetic operation are multiplication division and modulus modulus is the strange one for example system.out.println5%3 will print 2 this is because when 5 is divided by 3 the remainder is 2 modulus gives the remainder modulus also handles negatives the answer to a%b always has the same sign as a the sign of b is ignored pemdas the algebra rule pemdas applies to computer computations as well pemdas stands for the order in which numeric operations are done p parenthesis e exponents m multiply d divide a add s subtract actually m and d have equal precedence as do a and s for equal precedence operation proceed from left to right a mnemonic for pemdas is please excuse my dear aunt sally see appendix h for the precedence of all operators system.out.println5 3 4 -7 10 system.out.println8 56 3 5 -6 3 5 not the same as in algebra an unusual assignment consider the following count count +3 this is illegal in algebra however in computer science it means the new count equals the old count 3 int count =15 count count 3 system.out.printlncount 18
[close]