New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Computational Science JAVA

by: Alek Haley

Computational Science JAVA CS 3410

Marketplace > Utah State University > ComputerScienence > CS 3410 > Computational Science JAVA
Alek Haley
Utah State University
GPA 3.58

Linda Duhadway

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Linda Duhadway
Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 10 page Class Notes was uploaded by Alek Haley on Wednesday October 28, 2015. The Class Notes belongs to CS 3410 at Utah State University taught by Linda Duhadway in Fall. Since its upload, it has received 11 views. For similar materials see /class/230438/cs-3410-utah-state-university in ComputerScienence at Utah State University.

Similar to CS 3410 at Utah State University

Popular in ComputerScienence


Reviews for Computational Science JAVA


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/28/15
S Chapter 10 Arrays and Collections 2122009 5 Array Basics An array is a collection of data values If your program needs to deal with 100 integers 500 Account objects 365 real numbers etc you can use an array In Java an array is an indexed collection of data values of the same type g Arrays of Primitive Data Types An39ay Declaration ltdata typegt ltVarlablegt 13H ltdata typegt ltVarlablegt 1 atlom z An39ay Creation ltVarlablegt new ltdata typegt ltSlZegt Example Variation 1 Variation 2 double 1 rainfall double rainfall 1 Rainfall new doublnuz Rainfall new doublnuz An array is like an object g Accessing Individual Elements Individual elements in an array acoessed with the indexed expression double xalnial dnubln 12 ramfall01234567891011 ms Indexed ammoquot rainfall2 g wgetmw The index of the first position in an array is 0 Array Processing Samplel doubl U ralnfall new doubl UZ the Public consum length returns me mac 0 double annualAverag my canamy sum 0 for mt l o l lt ramfalllmgcn um i Systelnmutprmth ilnter the ralnfall for month 1m H quoti ramfall l scanner nAxtDoubl l sulnramfall l gt annualAveragg sum ralnfallla1gthy Array Processing Samplel Notice the difference between the Array class s public data member length and the String class s public method length rainfalength namelength Array Initialization Like other data types it is possible to declare and initialize an array at the same time mt number l 2 4 5 s l doubler sampllngData i 2443 399 123 45009 132 900 3123 22034 1303 StrmgU Wontth i quotJanuaryquot quotFebruaryquot quotMarchquot quotAprilquot May quotJungquot July quotAngus quotSeptembe cquot rquot quotOctoberquot quotNovemberquot December gt numb ength gt 4 samplingnataJength e 9 month ameJength 12 2122009 Variablesize Declaration Java we are not limited to figtltedsize array declaration The following code prompts the user for the size ofan array and declares an array of designated size mt sue mt 1 number systembunprmunwuow blg do you want the array7 vii sue scennernexc1nti number new mtrslze Arrays of Objects In Java in addition to arrays of primitive data types we can declare arrays of objects An array of primitive data is a powerful tool but an array of objects is even more powerful The use of an array of objects allows us to model the application more cleanly and logically The Person Class We will use Person objects to illustrate the use ofan array of objects Pexson latte latte new personi latte set zmeUMS Lattequotr u latte setGendexl F The Person cum suppons me set methods and gel latte set e mums Systm out pxlntlnl quotName v o latte get zmel Systm out pxlntlnl quotAge quot o latte gethgel Systm out puntlnl quotSex v o latte geccenaero Creating an Object Array 1 meme Code B mmnmys pexson new Pexson2 j allocatede person State of Memory After is executed Creating an Object Array 2 WW mun code WWWm m H nmemmmu person state 0 1 2 3 4 16171819 of Memory After is executed 2122009 Creating an Object Array 3 Menus Code refelegetopizszlzeoq pexsonl new pexsonlt person state 0 1 2 3 4 16171819 nnnnnnnnnn After is executed Person Array Processing Sample 1 Create Person objects and set up the person array Stung name npstx nt e gnax gendex fox 1m 1 u 1 lt pexson length m l System out pnntnlt Entex name My name soannex nesto 12140 In aata values 62 soannex naxtOr pexsonlll new pexsonlt pexsonlll set zme name age E pexsonh setceneezlt gendex wind youngest and oldest persons version 1 Stung nameOmemgest naneotowest nt mm a nameOmemgest naneotomest pexsoniui get zme0r ul mln max pexsoni getAgeo fox 1m 1 1 1 lt pexson mgth m l age pexsonh gethgeo 1f age lt mn i feund a youngex peson naneotyoungest pexsoniui gethmOr i e1se 2 age a max l Hlounu an one Alcoa max age naneotomest pexsonl l gebNmnEOr wind youngest and oldest persons version 2 nt mnIdx maxldx mnae the young arm onesr Liaison mlnIdx a maxldx a u fox 1m 1 a 1 1 lt pexson mgth m l f pexsonhl getugeo lt pexsonlmnIdx getAgeo l mnIdx 1 Hfmmrl a yummy nelson i e1se 1f pexsonlll getngeo gt pexsonimzxmxi gaugeo l maxldx 1 ma 1 vldet senson l pesonlmnazl 5 tne youngest ana nezsoninmmi wind youngest and oldest persons version 3 Pexson youngest omest Hymmgest ana maest person youngest oldest pexsoniui mlnIdx maxldx u fox 1m 1 1 1 lt pexson length m l f pexsonlll getugeo lt youngest getAgeo l youngest pmsonlllr Himmd u yourgar pexson i e1se 1f pexsonlll getAgeo a omest getAgeo l oldest pexsonh found an clue nexsou us the yxunges n i Object Deletion Approach 1 m mm senw m vosmn 1 to null Before is executed After is executed 2122009 Object Deletion Approach 2 Object Deletion Approach 3 st e pexson Jengtha 1 e pexson magma new m m m WWW mutt senseless We WWW semienneesi pesmnzsti senm mm m mm vexsontwlr mmww 1 pmquot 1 W ts Lemmas e mi pm 5 mm mm to me Iell by one pexsonllzstl mm mmquot Before is executed After is executed Before is executed After is executed Eaterson Array Processing Sample 3 The Standard For Loop int numbers 5 10 15 20 25 Misc int sum 0 whne pexsonhl i nun ss 39pexsonlll getuzmeo equalsUthtequot l forint i0 iltnumberslength i 1f pexsonlll null l we we sum numbersi System out pxlntanMs Latte was not 111 the mayquot else l system out pnntnltquoti ound Ms Lette at posltlon v o n l The ForEach Loop The ForEach Loop int numbers 5 10 15 20 25 forint oneNumber numbers int sum 0 sum oneNumber for int oneNumber numbers sum oneNumber Loops through each element in the numbers array Stores the value of that element in the local variable oneNumber The ForEach Loop Can use a foreach loop with an array ofobjecls Person studenls new Person8 studenls0new Person forPerson one students ifonenull SystemoutprintlnquotNo one herequot e se SystemoutprintlnonegetName 2122009 g The ForEach Loop The foreach loop goes through evem element Be careful about accessing a null reference Person students new Person8 students0new Person for Person value students sum valuegetAge Hi The ForEach Loop e foreach loop does not change the value of an element in the array int numbers 5 10 15 20 25 for int oneNumber numbers 5 value 12 10 15 20 for Int oneNumber numbers 25 rpm nIIl39 39 39 quot 39 g The ForEach Loop he foreach loop only allows access to the elements The elements cannot be changed g The ForEach Loop For an array of objects each element is actually a reference to an object The foreach loop cannot change the value of that reference For Person p person p null g The ForEach Loop The foreach loop can use the reference to make changes to the object forPerson p person psetName John g The ForEach Loop The foreach loop can use the reference to make changes to the object forPerson p person Systemoutpn39ntlnquotEniEr quotpgetNamequot39s age quot newAge scannernext1nt p5etAgenewAge 2122009 5 Restrictions of a ForEach Loop The for eachloop only allows access to the element The element cannot be changed The foreach loop allows access to only a single array The foreach loop iterates over every element of an array from the first to the last element We cannot use the foreach loop to access only a portion of an array or to access the elements in reverse order 2192009 g The createNewFiIe Method public boolean createNewFileO throws IOException S Atomically creates a new empty le named by this Chapter COntlnued abstract pathname ifand only ifa le with this name does not yet exist The check for the existence of the File Input and Output le and the creation of the le if it does not exist are a single operation that is atomic with respect to all other lesystem activities that might affect the le Returns true if the named le does not exist and was sucoessfully created false if the named le already ists 1 Using createNewFiIe Some File Methods u u Boolean exislso Flle outstream new Flle data39out Tsls whether the file or directory denoted by this abstract exists boolean isFile To see ii the File is associated to a lile or not ll lalse it is a outStreamcreateNewFIle directon or is not associated with a llle boolean IsDIrectoryO To see ii the File is associated to alile or not ll lalse it is alile catchIOExceptIon e 39 or Is not associated With a drrecton Systemoutprintln Error opening lequot Note that you can create a File object that does not yet exist Both isDirectonO and isFile will return false Getting The Absolute Listing Files in a Directory Pathname List the name of all files in the directory String QEEAbSDIUtEPBthO CiJaV3Pr le t5Ch12 Returns the absolute pathname string of this pathname String getCanonicaIPath Returns the canonical pathname string ofthis pathname Same as getAbsolutePathO exoept that it Removes redundant names such as quotand quot Resolves symbolic links under Unix for int i 07 i lt filenm length i Converts driver letters to uppercase on Windows Systemout printlnfilename i 7 File directory new FilequotCJavaProgramsCh12quot String filename directoryiist 7 2192009 Getting Pathname Components String getName Returns the name of the file or directory denoted by this tract pa name String getParent Returns the pathname string of this abstract pathname s parent or null if this pathname does not name a parent Read Write Access boolean canReadO ests whether the application can read the le denoted by this abstract pathname boolean canWriteO Tests whether the application can Irec r ie getParentFile Returns the abstractpathname of this abstract modlfy the le denoted by th395 abstract pathname39s parent or null if this pathname does not Pathname name a paren 39 y String getPath Converts th39 a pathname string 15 Open iii bl Lookln immune vi El D Mag 3 The J eChooser Class javaxswingJFileChooser Can produoe a popup window that displays the oomputers directory struc ure The user can move through this directory and select a le from it This le can then be associated with a File object in t e application E Uinlzlers nsual sunlm znns 1 m D mum 99999 rue ame Flies at Me All Flies Crea ng a J Chooser Object 39 VaxswingJFiIeChooserobjectallows the A Ja user to select a le JFlleChooser chooser new JF11eChooser i To start the listing from a specific directory JFlleChooser chooser 7 new FlleChooser quotDJavaProgramsChl2quot g Creating a JFileChooser Object 39 yuu can get a system property that returns a string that is the path to the current directory Sring current SystemgetProperty userdirquot Then we can use that Sring as the parameter when we create a JFileChooser JFileChooser chooser new JFileChoosercurrent This will set the beginning path at the JFileChooser to the 2192009 Open LlJ Lnukin mcrrzmmzexamme v l E D mum nlmrniect E D InlmleI D mumquot rue ame H i l The showOpenDialog Method int showOpenDialogComponent parent Pops up an quotOpen Filequot file chooserdialog Parameters parent the parent component of the dialog can be null see showDialog for details Returns the return state of the file chooseron popdown JFileChooserCANCEL70PTION JFileChooserAPPROVEioPTION JFileChooserERROROPTION if an error occurs or the dialog is dismissed Using showOpen Dialog he showOpenDialog method returns an integer that s whether the open button or the cancel button was clicked We can compare that value to the Class constants that store these va ues APPFl0VE70PTION CANCEL70PTON int status choosershow0penDialognull ilstatus JFileChooserAPPFl OPTIONX Systemoutprintn 0pen is clickedquot 3 to else Systemoutprintn Cance is clickedquot g The getSeIectedFile Method public File getSelectedFileO Returns the selected file This can be set either by the pro r ervia setFile or by a useraction such as either typing the filename into the UI or selecting the file from a list in the UI Retu ms the selected file Usrng getSeIectedFile Once we determine that the open button was selected we can access the selected File File selectedFile choosergetSelectedFie And the current directory File currentDirectow choosergetCurrentDirectonO File input String current SystemgetPropertyquotuserdirquot JFileChooser chooser new JFileChoosercurrent int status choosershow0penDialognull ifstatus JFileChooserAPPROVEOPTION input choosergetSelectedFile0 ifinputexists0 SystemoutprintlnquotFile Foundquot else SystemoutprintlnquotFile NOT Foundquot Object File IO It is possible to store objects just as easily as you store primitive data values We use ObjectOutputStreamand O a bjectInputStream to save to and load objects from le To save objects from a given class the class declaration must include the phrase implements Serializable For example class Person implements Serlallzable i Reading Objects Elle e new Elleriioojeecspsceui lnEllescreem new Ellelnpucscreem lnEllei Obj ecc lnpucscreem mobjeccscre n Ellelnpuc Stream em ew objectlnpucscreemrlnrllescreemi person person Personi lnomeecscreemreeoomeer i Account account Accountl mobjeccscreemreeoobjeccr i Bank bank Bankl lnobjeccscreemreeoobjecr i 2192009 Saving Objects Elle ouwlle new F11 t obj ctsdatequotiy Elleoucputscreem oumllescreem new Elleoucpucscreemroumllei objeccoucpucscreem oucobjeccscreem erson person new personmlr Espresso 20 w i outobjectstream wrlceomeecr person i account new Accountth bank new aenkti oucobjeccscreemwrlceobjecc accoun m i oucobjeccscreemwrlceobjeccr bank i new Ob eccoucpuc Stream outF lles cream Can 39gve39 orde nom me meremi chm I Saving and Loading Arrays Instead of processing arrav elemenm individuallv it i5 possible to save and load the Whole arrav at once personrl people new personrm Hessume ri else nes e would the people array saVlt rr oucobjec e rey csreemwrlceob3ecc people i less the exray personrl people personm lnomeecscreemreeaop3eecr i


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Allison Fischer University of Alabama

"I signed up to be an Elite Notetaker with 2 of my sorority sisters this semester. We just posted our notes weekly and were each making over $600 per month. I LOVE StudySoup!"

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.