Lab 4 Name: Checked: Objectives: Learn hw t test cde snippets interactively. Learn abut the Java API Practice using Randm, Math, and String methds and assrted ther methds frm the Java API Part A. Use jgrasp t test sme cde snippets It is smetimes useful t try smething ut withut writing a whle prgram. jgrasp has an Interactins tab that allws yu t d that. Open jgrasp and click n Interactins tab (lwer part f windw). Experiment typing a few f each f the fllwing, nting results n this wrksheet as yu g alng. arithmetic expressins 4 + 3 4 / 3 (duble) 4 / 3 (duble) (4 / 3) variable declaratins, assignments int a = 1 int b = 2 int c = 3; // Nte: semicln is ptinal here a = c c = 5 Yu can type any expressin t get its value; type variable names t get their values: a b c Java expressins, invlving Math and String classes. Try the fllwing and nte the results: duble phi = Math.PI / 3 Math.sin(phi) Math.cs(phi) String name = "Grace" Tips: Watch the Wrkbench tab n the tp/left part f the windw; it lists yur variables and their values. T avid re- typing a line f cde, use the up- arrw ne r mre times it remembers the previus lines f cde yu entered. Java expressins that have a value can be evaluated directly. Statements r directives that have n value need a semicln. Example: imprt java.util.randm; if (a > 0) ans = yes ; name.length() name.charat(1)
name.charat(0) name.substring(2,4) name.tuppercase() Java statements: if (a > b) System.ut.println(a); else System.ut.println(b); Output: int n = 0; while (n < name.length()) { System.ut.println(name.charAt(n)); n++; } Output: Imprt directives imprt java.util.randm; imprt java.text.numberfrmat; Mre Java expressins, using Randm and NumberFrmat classes. Try the fllwing and nte the results: Randm rand = new Randm() rand.nextint(4) rand.nextint(4) // repeat a few times... rand.nextflat() NumberFrmat mney = NumberFrmat.getCurrencyInstance() NumberFrmat percent = NumberFrmat.getPercentInstance() duble amunt = 0.83; mney.frmat(amunt) percent.frmat(amunt) Ntes abut ther things yu tried:
Part B: Java prgrams using String methds 1. Write a Java prgram that asks yur name and then prints it ut ne letter per line. Fr example, an interactin might lk like this: Please enter yur name: Grace Hell... G r a c e 2. Write a Java prgram that asks yur name and then prints it backwards. Fr example, an interactin might lk like this: Please enter yur name: Grace Hell ecarg 3. Write a Java prgram that cunts the number f vwels in sme text. Fr example, an interactin might lk like this: Please enter sme text: It is never t late t have a happy childhd. This text cntains 16 vwels. Hint: Yu need t check each character in the String t find ut if it is a vwel, i.e., whether it equals a r it equals e, etc. 3. Mdify the previus prgram t perfrm its I/O using JOptinPane. Yu will need t imprt javax.swing.joptinpane. Here is sme cde t get yu started: String sentence; // the input sentence int num; // the number f vwels sentence = JOptinPane.shwInputDialg("Enter a sentence"); //... // cde t calculate number f vwels //... JOptinPane.shwMessageDialg (null, "Yur sentence has " + num + " vwels");
Part C: Java API exercise (hmewrk) Java derives much f its pwer frm the many classes already defined in the Java Applicatin Prgramming Interface (aka Java API). But hw are we ever t learn and use these classes if we dn t knw abut them? Any textbk n Java can nly begin t cver these classes and the methds defined in them. Fr a cmplete listing f these classes and methds yu will need t visit the Java 6 API: http://dcs.racle.cm/javase/7/dcs/api/ Althugh the infrmatin cvered in the textbk is sufficient t cmplete all f the prgramming and lab assignments fr this curse, yu may find yurself wishing fr a better class r methd, r just mre infrmatin n a knwn class r methd. The Java API website (see link abve) is the place t find that infrmatin! All class definitins are fund in the Java API Specificatins. API stands fr applicatin prgramming interfaces and is mre simply a set f existing building blcks fr prgramers t use t develp prgrams. The API is divided int packages. Packages cntain classes. Classes cntain methds. Methds cntain Java cde. We use methds in ur Java prgrams. Access the Java API at the link abve. Why is it abbreviated t Java SE (what des the SE stand fr)? The API Specificatins page is divided int 3 sectins. The upper left-hand sectin is used t navigate t different packages (cllectins f classes). Belw this sectin is a listing f all Java classes in alphabetical rder. The largest sectin f the page displays details abut a selected package r class. At present (befre selecting a class r package), all Java packages are listed. Scrll dwn the main display sectin f the page until yu find the java.lang package. What des it prvide? The java.lang package is autmatically prvided/imprted fr all Java prgrams. Find the java.util package. What des it prvide? _
Clicking n any package will get a detailed descriptin f the package. Click n java.util. This detailed descriptin prvides 5 summaries f items cntained in this package. List the fur summaries which are written in the range backgrund: Fr nw, we are interested in the Class Summary. This summary lists the classes that are cntained in the package. The left clumn cntains the name f the class. Ntice that all class names start with a capital letter. The right clumn cntains the descriptin f the class. Scrll dwn until yu find the Scanner class. What des it cntain? Click n the Scanner class. Yu will get a detailed descriptin f what is cntained in the Scanner class. Ntice that the package name - java.util - appears (in small print) abve the class name. Scrll dwn a few pages t see the tw summaries available fr the Scanner class. What are they? Scrll dwn t the Methd Summary. The left clumn indicates the type f infrmatin the methd will return. The right clumn cntains the methd name (underlined), the parameters (in parentheses) and a brief descriptin f the methd. Examine the first methd listed fr the Scanner class. It is the clse() methd. The left clumn cntains vid, indicating that this particular methd des nt return anything. All methds have a return type, even if the return type is simply vid. The right clumn tell us the name f the methd is clse and the empty () indiciates that this methd des nt require any parameters t be used. The name f the methd is lcated immediately befre the pen parenthesis. All methds require parentheses. Based n this infrmatin, yu culd invke this methd using the prgramming statement scan.clse(); where scan is an already declared and intialized Scanner bject. Let s lk at anther Scanner methd. Lcate the methd findinline(). As yu can see, there are tw versins f this methd, bth f which return a String. Lk at the versin with a parameter f type String named pattern. The definitin tells us that this methd attempts t find the next ccurrence f a pattern cnstructed frm the specified string, ignring delimiters.
Based n this infrmatin, yu culd invke this methd using the prgramming statement String result = scan.findinline( xx ); where scan is an already declared and initialized Scanner bject. The variable result will then reference the String prduced/returned by the methd. Click n the name f the Scanner methd findinline(). This will prvide yu additinal infrmatin abut the methd. Ntice the line at the tp f the page: public String findinline( String pattern) This line is knwn as the methd header. This is the same infrmatin that we saw in the methd summary with the added wrd public. The wrd public indicates that this methd is publically assessible s that we can use it. The return type fllws and is a String. A methd nly ever retuns ne type. The wrd lcated immediately befre the parentheses is the name f the methd. Everything listed inside f the parentheses are the parameter specificatins. Chse yur brwers s back buttn t return t the Scanner class s Methd Summary. Let s lk at ne mre methd f the Scanner class. T date, we have used the nextint() methd t capture integer input frm the user. Lcate the nextint() methd. This methd is interesting because it is listed twice. The first appearance f this methd des nt specify a parameter and the secnd appearance f the methd des. Nte that bth nextint() methds return an integer. If yu have a Scanner bject declared and initilaized called scan and an integer declared and intialized call num, the nextint() methd culd be invked ne f tw ways: int inputa = scan.nextint(); int inputb = scan.nextint( num ); Ok nw let s lk at anther class the String class. T lcate the String class, use the left hand alphabetically listing f classes. What package is the String class part f? Under the String class Methd Summary, lcate the String methd trim(). Fr this methd, prvide the fllwing: Methd return type: Required paramaters fr the methd: Purpse f the methd: What wuld be displayed as a result f executing the fllwing prgramming statements? String fname = "Ben ", lname = "Franklin"; System.ut.println( fname + lname); System.ut.println( fname.trim() + lname); There are s many great methds t be used frm the String class that yu will surely return t this class s API many times! But befre yu review mre r the String methds, let s take a lk a lk at a special type f class. The Math class is a class that nly cntains static methds. First, lcate the Math class. In which Java package can yu find the Math class?
Scrll dwn t the Methd Summary sectin f the Math class. Examine the first methd called abs(). The left clumn cntains static duble. The wrd duble tells us that the return type f the methd is duble. But what des static mean? Static tells us that this methd des nt act n an bject frm the Math class but that we can just call this methd whenever needed. First, answer these questins abut abs(): Methd return type: Required paramaters fr the methd: Purpse f the methd: Because abs() is a static methd, t invke the methd yu wuld use the class name and then the methd. Fr example, executing System.ut.println( Math.abs( 3-10) ); wuld result in 7. Review the Math methd ceil() and answer these questins: Methd return type: Required paramaters fr the methd: Purpse f the methd: Example f invking the methd: Java API - What have yu learned? The Java API is divided int packages Packages cntain classes Class names start with a capital letter Classes cntain methds The name f the methd is directly t the left f the pen parenthesis All methds require parenthesis Parameters are specified with a type fllwed by an identifier All methds have a return type The return type f the methd is lcated directly t the left f the methd name