PRIN OF COMPUTER PROGRAMMING
PRIN OF COMPUTER PROGRAMMING CSC 2310
Popular in Course
Popular in ComputerScienence
This 14 page Class Notes was uploaded by Mallie Crist on Monday September 21, 2015. The Class Notes belongs to CSC 2310 at Georgia State University taught by Staff in Fall. Since its upload, it has received 15 views. For similar materials see /class/209895/csc-2310-georgia-state-university in ComputerScienence at Georgia State University.
Reviews for PRIN OF COMPUTER PROGRAMMING
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: 09/21/15
Chapter 5 Arrays Arrays is one of the simplest data structure in JAVA It is used to store data in a celllike manner The array s cell starts from 0 to as the following example will show Name of array A 4 7 8 0 1 2 39253121 3 4 5 6 7 8 Array index The index of the array let you manipulate the array ie retrieve data and store data in the array An array can be of any data type integer double character and objects like string etc Arrays are ideal to hold data as in a database One important aspect of arrays is that it must only contain a single data type That is if an array is declared to be of type integer then only integer data type must be stored inside the array To create an array we need to declare it bearing in mind the type of data we would be storing inside of the array For example if we want an array to store integer numbers we would declare an array as follows int a and now declare the size of the array as followsif we wanted 10 elements in the array a new int10 Note we could have made a single declaration as follows int a new int10 OR int n 10 int a new intn Also the value in the square brackets could be any expression that must evaluate to an integer We could have also initialized the array when it was declared mm a 0 0 0 0 0 0 0 0 0 0 Similarly we could have declared a string array as follows String name OR and initialize it immediately String name quotjohnquot Array Subscripting As shown above each element of an array has an index It is this index that is used to retrieve or store data in that particular location The indexing starts from 0 and goes to the full size of the array minus 1 The subscripting of an array is written as ai where a is the name of the array and i is any integer value or any expression that must evaluate to an integer value To initialize an array we could accomplish this in two ways Ifwe know the values we want to initialize the array with we could do so when we declare the array as shown above If we do not know the values then we would need to use a loop to do so We could either use a while loop or a for loop to do so In either case we would need to know what the length of the array is To nd the length of the array we could either use the value that was used when the array was declared or we could use the length function We must note however that when we are using the length function we would not place the brackets at the end of length as we would normally do when we call functions The following example shows the correct way first and the wrong way second int X alength NOT int x alength First using a while loop with an array The following program will demonstrate the use of the while loop to create an array and then access the data of the array import jpb public class AverageGrade public static void mainString args int i sum numberOiCrades String userInput int grades SimpleIOpr0mptquotEnter the number of grades you want to average quot userInput SimpleIOreadLinetrim numberOfGrades IntegerparseInt userInput grades new intnumberOiGrades int grades new intnumberOfGrades i 0 while i lt gradeslength SimpleIOpr0mptquot Enter grade quot i 1 quot quot userInput SimpleIOreadLinetrim gradesi IntegerparseInt userInput i while i lt gradeslength sum gradesi l SystemoutprintlnquotnThe average of the grades you have entered is quot sumgradeslength The for Loop This loop is used mainly for counting or to process a data structure whose size length is known or could be obtained by using a function call that will return the size length of the data structure A for loop has the following format for initialization test condition for exiting the loop updating Note If the test condition evaluates to true then you would enter the loop and carry out the statements Else you would exit the loop A for loop can have all three of these conditions inside of the parenthesis or none or any combination However the semicolons present inside of the parenthesis regardless of how many parameters are used Also if these conditions do not exist inside of the parenthesis they must be found inside of the for block Also note that if there is no exit condition or the exit condition cannot be evaluated properly you would have an in nite loop something that you do not want Example int n 20 for int i 0 i lt n i Systemoutprintlni This loop will execute for 20 times 7 starting from 0 to 19 So the output of this slice of code would be a list of numbers starting from 0 and going tol9 OR using block in for loop intn20j0k0 for int i 0 ilt n i j i i k Mathpowj 2 Systemoutprintln The results are i k For loops can also be nested Example Selection Sort import javaio public class sorting public static void mainString args int num 22567984532101997310 int i j temp min minindex movesl moves2 comp movesl O moves2 O comp O fori O i lt 9 i min numi minindex i forj l l j lt 10 j if numj lt min min numj minindex j movesl comp if min lt numi temp numi numi min numminindex temp moves2 comp SystemoutprintlnquotThe sorted list is quot for i O i lt 9 i Systemoutprint numi quot quot System out println Systemoutprintln 39The number of inner moves quot movesl SystemoutprintlnquotThe number of comparisons quot comp SystemoutprintlnquotThe number of outer moves quot moves2 Accessing Array Elements Two ways to access array elements 1 Seguentially and 2 Randomly l sequentially Going through the array element by element using either a for loop or a while loop ExamEle The following loop searches an array name array for the first occurrence of the number 100 and then break out of the loop int i for i O i lt arraylength i if arrayi 100 break Of course we may add a little bit more code to this example to produce some sort of a result 2 Randomly Being able to access any element of the array regardless of that element s index location Example arraylO or array20 or the example program Arrays as vectors We could use a1rays as vectors which would eventually let us use arrays to create matrices and other multidimensional data structures We could scale an array vector by multiplying that array with a constant value Add two arrays and compute the dot product of two arrays All of these could be done with the use of a for loop Arrays as database Using parallel arrays to create a database NOT A GOOD IDEA The best structure to use is an array of objects Example We could modify the Account class of page 92 to give a BankAccount class where the constructor could create objects with more than one parameter Public class BankAccount private String lName lName address accountNumber private double initialBalance public BankAccountString X String y String 2 double a lName x fName y accountNumber z initialBalance a public BankAccountO lName Doe fName John accountNumber 000000000 initialBalance 00 To create an array of objects ie an array with 100 objects BankAccount accounts new BankAccount100 Note The actual value in the array will be addresses to where these objects can be located Adding a record to the DataBase If int numAccounts 0 accountsnumAccounts new BankAccount Brown Jane 111222 333 100000 numAccounts Chapter 3 Objects as Models Java is a purely objectoriented language thus everything in Java is modeled via classes Objects An object has two basic properties 1 State an object contains one or more items of information 2 Behavior an object has behavior 7 it responds to operations that are performed on it Some of these operations may change the state of it Representing Objects within a program The state of an object is stored as instance variable and the behavior is represented as instance methods The instance variables keep track of the state of the object They could be variables that stores a single value for example and integer value or variables that store an entire object Operations would be carried out on each object To do this we use the instance methods To invoke an instance method we use the name of the object followed be a period and then the name of the method For example if the name of the object was account and a method inside this object was deposit then to use it we would write something similar to the following accountdeposit Classes Both the instance variables and instance methods are grouped into a class Declaring a class is as follows public class class name variable declarations constructor declarations method declaration Using the example in the notes for account public class Account variable declarations constructor declarations method declarations These declarations are usually preceded by an access modi er pnblic or private These would indicate whether if the associated declarations are for use privately only ie to be used within this class only 7 private or could be accessed by other classes ie available publicly It is advisable to declare all instance variable to be private Example private double balance This is to facilitate information hiding The out side cannot see what is stored in balance as well as by not having access to it it cannot be changed by the out side world Declaring Instance methods public void deposit double amount Access modi er The word public means that the method could be used called anywhere in the program not only the class in which it is de ned Result type indicate what type of answer the method will output return when the method is called Method name The name can be any legal identi er Parameters A method can have any number of parameters form 0 to of any data type including user de ned type When a method is declared these are called parameters When the method is called the values passed are regarded as arguments Let us declare a class name Sword public class Sword private String description used to give the sword a descriptive name private int weight used to store the weight of the sword private int damage used to store the amount damage the sword can do private int magicDamage used to store the magical damage the sword can do now put here the class methods Method Overloading and Method Overriding These two aspects are together regarded as polymorphism which is inherent to any obj ect oriented language Overloading Java allows any amount of methods with the same name to be declared inside a program or class The only restriction which is very important is that the method must have either 1 A different a amount of parameters OR 2 Different data types OR 3 A combination of the above two Note Ifquot two methods have the same name and parameters but different return types this will create a problem when compiling the program The compiler will complain something to the effect that you have duplicate method declaration The difference in the return type does not mean that the methods are different Example Suppose these methods exist in a base class called Item public void printDescriptionO no parameters Systemoutprintlndescription public void printDescriptionint index one parameter String itemString new IntegerindextoString converts an integer to string SystemoutprintlnitemString description Overriding virtual functions Method overloading applies within a single class but method overriding applies to different classes related via inheritance In this case the two methods may have the same name and same parameter list provided that they are in different class 7 usually a base class and a derived class Thus if the method is called on an instance on the base class then the base class method is used But if the method is called on an instance on the derived class then the base class method is override and the derived class is used Example If we added the following method to the Sword class public void printDescriptionO no parameters Systemoutprintlndescription Systemoutprintln Damage damage Systemoutprintln Magical Damage magicDamage Here the printDescription method of the Sword class will override the printDescription ofthe Item class because the Sword class is a derived class ofthe base class Item As such if a call is made for the printDescription base upon the Sword class then the method de ned in the Sword class is used Inheritance As indicated above a base class offers its instance variables and methods to the derived class The reason for a base class and thus inheritance is that very often a program may require many classes to be de ned but there may be some amount of relationship between these classes The common relationships could be de ned in the base class and then these be offered to all of the other classes that may need them There are two important features about creating a base class and a derived class as the following example will show public class Item String description n0te the absence of the accessor word private int weight n0te the absence of the accessor word private public String getDescriptionO return description public void setDescripti0nString newDescription description newDescription Now for the declaration of the Sword class public class Sword extends Item n0te the use of extends Item private int damage private int magicDamage public int getDamageO return damage public void setDamageint newDamage damage newDamage Declaring constructors Whenever a new object is created the instance variables are initialized by a constructor l Constructors may or may not have parameters 2 A constructor has no return type 3 The name of the constructor must be the same name of the class in which it is declaredde ned A class may have more than one constructor provided that they have different amount of parameters and or data type 5 Having more than one constructor can be advantageous 7 one can initialize the instance variable to zero 4 Constructors are called with the new operator This is used to dynamically create space memory for a new object Let us de ne constructors for the Item class and the Sword class public class Item String description note the absence of the accessor word private int weight note the absence of the accessor word private Item this is a default constructor or paramaterless description General item weight 0 Item String initDescr int initWeight this will allow the user to initialize the values description initDescr weight initWeight public String getDescription return description public void setDescriptionString newDescription description newDescription public class Sword extends Item note the use of extends Item private int damage private int magicDamage Sword String initDescr int initWeight int initDamage int initMagicDamage superinitDescr initWeight damage initDamage magicDamage initMagicDamage public int getDamage return damage public void setDamageint newDamage damage newDamage Because Sword is a derived class the constructor from Item is called to initialize the two common variables 7 description and weight The constructor for Sword now only has to initialize the other two variables that are locale to it Note If no explicit call as in the above case is made to super then an implicit call to the parameterless constructor of the base call would be made as the rst statement in the derived class constructor If the base class has a userde ned constructor with arguments but no argumentless constructor then a compiler error will occur Now we can create objects for both the Item and Sword classes as follows Item defaultItem new Item Item specifyItem new Item My new item 50 Sword mySword new Excalibur 40 10 15 Java String Class The string class package in java is probably one of the most important packages available To use the methods found in this package you will use the javalang package Note this package is automatically imported into your program when you import the javai0 package So on creating string variables we declare them similar to creating integer or double example String lastName rstName middleName Q String lastName rstName middleName In this last case we have initialize lastName t0 the blank or empty We could assign a value to a string variable firstiName John Note the use of the quote around john Also a string object could be created without the use of the word new A string could be visualized as an array holding the individual characters example rstName could be visualized as the following array n 0 l 2 3 These are the index position starting from 0 We can now extract individual characters from the name JOHN example char x x firstiNamecharAt2 now x will hold the value found at position 2 7 h We use the charAtint function to access the value at the position supplied in this case 2 Other functions of immediate importance are listed on page 110 Note also when you call a function of the string class you must follow the following format Objectnamestringfuncti0nstring parameters If we look at the above example The 0bjectname was firstName followed by the dot Stringfuncti0n was charAt String parameter was integer 2 If a string function is used to search for a substring the value returned would be an index integer indicating where that substring is located If that substring was not found the return value would be 71 The trim method is very useful if you want to remove blank spaces from the beginning andor end of a word Example if lastName Helper with 2 blank spaces at both before and after Then lastName lastNametrim Would now make lastName Helper with no leading 0r ending blanks Using to concatenate This is one of the most versatile use for in Java It can be used to put two strings together making one string Example String fLName fLName rstName lastName will produce John Helper But we could also use it to concatenate a string with an integer example System0utprintn This is the value of integer value The operator will automatically convert the integer value to a string and then concatenate them to produce the result The operator automatically invoke the t0String method to convert an object to string We could have done it explicitly by the following If f was an object of type Fraction then ft0String would convert whatever value was returned by this call to a string The use of the operator must be cautious in that the following must be observed 1 At least one of the rst two operands to be concatenated must be a string 2 You could concatenate more than two items providing that you observe 1 3 Use to do regular addition providing that at least two consecutive operand are numerical To reduce the use of println when the sentence is too large to t on one line example Systemout println If this sentence is too long to be placed on one line then feel free to separate it analputlit on two dyfkrent lines or even three lines 5 The could be used to add a value to the end of a string example rstiName lastiName producz39ng JohnHelperno space between 4
Are you sure you want to buy this material for
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'