id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
20,700 | second_true_statement else false_statement if the first boolean expression is falsethe second boolean expression will be testedand so on an if statement can have an arbitrary number of else if parts for examplethe following is correct if statement if (snowlevel gotoclass()comehome()else if (snowlevel gosledding()havesn... |
20,701 | breakcase tuesystem out println("this is getting better ")breakcase wedsystem out println("half way there ")breakcase thusystem out println(" can see the light ")breakcase frisystem out println("now we are talking ")breakdefaultsystem out println("day off ")breakthe switch statement evaluates an integer or enum express... |
20,702 | java provides for three types of loops while loops the simplest kind of loop in java is while loop such loop tests that certain condition is satisfied and will perform the body of the loop each time this condition is evaluated to be true the syntax for such conditional test before loop body is executed is as followswhi... |
20,703 | here is the syntax for java for loopfor (initializationconditionincrementloop_statement where each of the sections initializationconditionand increment can be empty in the initialization sectionwe can declare an index variable that will only exist in the scope of the for loop for exampleif we want loop that indexes on ... |
20,704 | numapples apples getnumapples ()for (int numapplesx++eatapple (apples getapple ( ))spitoutcore ()in the java example abovethe loop variable was declared as int before each iterationthe loop tests the condition numapplesand executes the loop body only if this is true finallyat the end of each iteration the loop uses the... |
20,705 | illustrates this casepublic void getuserinput(string inputdo input getinputstring()handleinput(input)while (input length()> )notice the exit condition for the above example specificallyit is written to be consistent with the rule in java that do-while loops exit when the condition is not true (unlike the repeat-until c... |
20,706 | it follows that the return statement must be the last statement executed in functionas the rest of the code will never be reached note that there is significant difference between statement being the last line of code that is executed in method and the last line of code in the method itself in the example abovethe line... |
20,707 | foundflag truebreak zerosearchreturn foundflagthe example above also uses arrayswhich are covered in section the continue statement the other statement to explicitly change the flow of control in java program is the continue statementwhich has the following syntaxcontinue labelwhere label is an optional java identifier... |
20,708 | video game in figure figure an illustration of an array of ten (inthigh scores for video game such an organization is quite usefulfor it allows us to do some interesting computations for examplethe following method adds up all the numbers in an array of integers/*adds all the numbers in an integer array *public static ... |
20,709 | another simple use of an array in the following code fragmentwhich counts the number of times certain number appears in an array/*counts the number of times an integer appears in an array *public static int findcount(int[aint kint count for (int ea/note the use of the "foreachloop if ( = /check if the current element e... |
20,710 | comparisons succeed declaring arrays one way to declare and initialize an array is as followselement_type[array_name {init_val_ ,init_val_ ,init_val_n- }the element_type can be any java base type or class nameand array_name can be any value java identifier the initial values must be of the same type as the array for ex... |
20,711 | (recall that arrays in java always start indexing at )andlike every array in javaall the cells in this array are of the same type--double arrays are objects arrays in java are special kinds of objects in factthis is the reason we can use the new operator to create new instance of an array an array can be used just like... |
20,712 | if insteadwe wanted to create an exact copy of the arrayaand assign that array to the array variablebwe should write clone()which copies all of the cells of into new array and assigns to point to that new array in factthe clone method is built-in method of every java objectwhich makes an exact copy of that object in th... |
20,713 | exercise - simple input and output java provides rich set of classes and methods for performing input and output within program there are classes in java for doing graphical user interface designcomplete with pop-up windows and pull-down menusas well as methods for the display and input of text and numbers java also pr... |
20,714 | considerfor examplethe following code fragmentsystem out print("java values")system out print( )system out print(',')system out print( )system out println((double,char,int")when executedthis fragment will output the following in the java console windowjava values , (double,char,intsimple input using the java util scann... |
20,715 | system out print("enter your weight in kilograms")float weight nextfloat()float bmi weight/(height*height)* system out println("your body mass index is bmi ")when executedthis program could produce the following on the java consoleenter your height in centimeters: enter your weight in kilograms your body mass index is ... |
20,716 | and even look for patterns within lines while doing so the methods for processing input in this way include the followinghasnextline()returns true if and only if the input stream has another line of text nextline()advances the input past the current line ending and returns the input that was skipped findinline(string )... |
20,717 | creditcard class defines five instance variablesall of which are private to the classand it provides simple constructor that initializes these instance variables it also defines five accessor methods that provide access to the current values of these instance variables of coursewe could have alternatively defined the i... |
20,718 | the test class |
20,719 | output from the test class |
20,720 | nested classes and packages the java language takes general and useful approach to the organization of classes into programs every stand-alone public class defined in java must be given in separate file the file name is the name of the class with java extension so classpublic class smartboardis defined in filesmartboar... |
20,721 | class as nested class inside the definition of the text editor class keeps these two highly related classes together in the same file moreoverit also allows each of them to access nonpublic methods of the other one technical point regarding nested classes is that the nested class should be declared as static this decla... |
20,722 | import ta measures thermometerimport ta measures scaleat the beginning of project package to indicate that we are importing the classes named ta measures thermometer and ta measures scale the java run-time environment will now search these classes to match identifiers to classesmethodsand instance variables that we use... |
20,723 | design coding testing and debugging we briefly discuss each of these steps in this section design the design step is perhaps the most important step in the process of writing program for it is in the design step that we decide how to divide the workings of our program into classeswe decide how these classes will intera... |
20,724 | human eyes onlyprior to writing actual code such descriptions are called pseudocode pseudo-code is not computer programbut is more structured than usual prose pseudo-code is mixture of natural language and high-level programming constructs that describe the main ideas behind generic implementation of data structure or ... |
20,725 | important steps like many forms of human communicationfinding the right balance is an important skill that is refined through practice coding as mentioned aboveone of the key steps in coding up an object-oriented program is coding up the descriptions of classes and their respective data and methods in order to accelera... |
20,726 | if we are fortunateand our program has no syntax errorsthen this compilation process will create files with classextension if our program contains syntax errorsthen these will be identifiedand we will have to go back into our editor to fix the offending lines of code once we have eliminated all syntax errorsand created... |
20,727 | comment about that classvariableor method code fragment an example class definition using javadoc-style comments note that this class includes two instance variablesone constructorand two accessor methods |
20,728 | @author textidentifies each author (one per linefor class |
20,729 | @exception exception-name descriptionidentifies an error condition that is signaled by this method (see section @param parameter-name descriptionidentifies parameter accepted by this method @return descriptiondescribes the return type and its range of values for method there are other tags as wellthe interested reader ... |
20,730 | sophomore public static final int junior /code for junior public static final int senior /code for senior /instance variablesconstructorsand method definitions go here indent statement blocks typically programmers indent each statement block by spacesin this book we typically use spaceshoweverto avoid having our code o... |
20,731 | the correctness of program over all possible inputs is usually infeasiblewe should aim at executing the program on representative subset of inputs at the very minimumwe should make sure that every method in the program is tested at least once (method coverageeven bettereach code statement in the program should be execu... |
20,732 | that returns fixed string debugging the simplest debugging technique consists of using print statements (using method system out println(string)to track the values of variables during the execution of the program problem with this approach is that the print statements need to be eventually removed or commented out befo... |
20,733 | each payment - modify the creditcard class from code fragment to charge late fee for any payment that is past its due date - modify the creditcard class from code fragment to include modifier methodswhich allow user to modify internal variables in creditcard class in controlled manner - modify the declaration of the fi... |
20,734 | integers smaller than - write short java function that takes an integer and returns the sum of all the odd integers smaller than creativity - write short java function that takes an array of int values and determines if there is pair of numbers in the array whose product is odd - write java method that takes an array o... |
20,735 | times write java stand-alone program that will write out the following sentence one hundred times" will never spam my friends again your program should number each of the sentences and it should make eight different random-looking typos - (for those who know java graphical user interface methodsdefine graphicaltest cla... |
20,736 | object-oriented design contents goalsprinciplesand patterns object-oriented design goals |
20,737 | design patterns inheritance and polymorphism inheritance polymorphism using inheritance in java exceptions throwing exceptions catching exceptions |
20,738 | interfaces and abstract classes implementing interfaces multiple inheritance in interfaces abstract classes and strong typing casting and generics casting generics exercises |
20,739 | goalsprinciplesand patterns as the name impliesthe main "actorsin the object-oriented design paradigm are called objects an object comes from classwhich is specification of the data fieldsalso called instance variablesthat the object containsas well as the methods (operationsthat the object can execute each class prese... |
20,740 | complications resulting from their radiation overdose all six accidents were traced to software errors adaptability modern software applicationssuch as web browsers and internet search enginestypically involve large programs that are used for many years softwarethereforeneeds to be able to evolve over time in response ... |
20,741 | the notion of abstraction is to distill complicated system down to its most fundamental parts and describe these parts in simpleprecise language typicallydescribing the parts of system involves naming them and explaining their functionality applying the abstraction paradigm to the design of data structures gives rise t... |
20,742 | in addition to abstraction and encapsulationa fundamental principle of object oriented design is modularity modern software systems typically consist of several different components that must interact correctly in order for the entire system to work properly keeping these interactions straight requires that these diffe... |
20,743 | one of the advantages of object-oriented design is that it facilitates reusablerobustand adaptable software designing good code takes more than simply understanding object-oriented methodologieshowever it requires the effective use of objectoriented design techniques computing researchers and practitioners have develop... |
20,744 | divide-and-conquer (section prune-and-searchalso known as decrease-and-conquer (section brute force (section the greedy method (section dynamic programming (section likewisesome of the software engineering design patterns we discuss includeposition (section adapter (section iterator (section template method (sections a... |
20,745 | methodsa() ()and (suppose we were to define classt that extendss and includes an additional fieldyand two methodsd(ande(the classt would theninherit the instance variablex and the methodsa() ()andc(froms we illustrate the relationships between the classs and the classt in aclass inheritance diagram in figure each box i... |
20,746 | description of itselffor to convert itself to stringor for to return the value of one of its data fields the secondary way that can interact with is for to access one of ' fields directlybut only if has given other objects like permission to do so for examplean instance of the java class integer storesas an instance va... |
20,747 | because the caller of (does not have to know whether the object refers to an instance of or in order to get the (method to execute correctly thusthe object variable can be polymorphicor take many formsdepending on the specific class of the objects it is referring to this kind of functionality allows specialized class t... |
20,748 | same way but it could require that we override the sniff methodas bloodhound has much more sensitive sense of smell than standard dog in this waythe bloodhound class specializes the methods of its superclassdog extension in using extensionon the other handwe utilize inheritance to reuse the code written for methods of ... |
20,749 | that class java provides keywordcalled thisfor such reference reference this is usefulfor exampleif we would like to pass the current object as parameter to some method another application of this is to reference field inside the current object that has name clash with variable defined in the current blockas shown in t... |
20,750 | way of identifying the current value as well we begin by defining classprogressionshown in code fragment which defines the standard fields and methods of numeric progression specificallyit defines the following two long-integer fieldsfirstfirst value of the progressioncurcurrent value of the progressionand the followin... |
20,751 | nextwe consider the class arithprogressionwhich we present in code fragment this class defines an arithmetic progressionwhere the next value is determined by adding fixed incrementincto the previous value arithprogression inherits fields first and cur and methods firstvalue(and printprogression(nfrom the progression cl... |
20,752 | class for arithmetic progressionswhich inherits from the general progression class shown in code fragment geometric progression class let us next define classgeomprogressionshown in code fragment which steps through and prints out geometric progressionwhere the next value is determined by multiplying the previous value... |
20,753 | determine the next value hencegeom progression is declared as subclass of the progression class as with the arith progression classthe geomprogression class inherits the fields first and curand the methods firstvalue and printprogression from progression code fragment progressions class for geometric |
20,754 | as further examplewe define fibonacciprogression class that represents another kind of progressionthe fibonacci progressionwhere the next value is defined as the sum of the current and previous values we show class fibonacciprogression in code fragment note our use of |
20,755 | different way of starting the progression code fragment progression class for the fibonacci in order to visualize how the three different progression classes are derived from the general progression classwe give their inheritance diagram in figure |
20,756 | inheritance diagram for class progression and its subclasses to complete our examplewe define class testprogressionshown in code fragment which performs simple test of each of the three classes in this classvariable prog is polymorphic during the execution of the main methodsince it references objects of class arithpro... |
20,757 | progression classes program for testing the code fragment output of the testprogression program shown in code fragment |
20,758 | exceptions exceptions are unexpected events that occur during the execution of program an exception can be the result of an error condition or simply an unanticipated input in any casein an object-oriented languagesuch as javaexceptions can be thought of as being objects themselves throwing exceptions in javaexceptions... |
20,759 | it is often convenient to instantiate an exception object at the time the exception has to be thrown thusa throw statement is typically written as followsthrow new exception_type(param param param - )where exception_type is the type of the exception and the param ' form the list of parameters for constructor for this e... |
20,760 | the exceptions / don' have to try or catch /which goshopping(might throw because /getreadyforclass(will just pass these along makecookiesforta() function can declare that it throws as many exceptions as it likes such listing can be simplified somewhat if all exceptions that can be thrown are subclasses of the same exce... |
20,761 | main_block_of_statements catch (exception_type variable block_of_statements catch (exception_type variable block_of_statements finally block_of_statements where there must be at least one catch partbut the finally part is optional each exception_type is the type of some exceptionand each variable is valid java variable... |
20,762 | problem /this code might have string tobuy shoppinglist[index]catch (arrayindexoutofboundsexception aioobxsystem out println("the index "+index+is outside the array ")if this code does not catch thrown exceptionthe flow of control will immediately exit the method and return to the code that called our method therethe j... |
20,763 | care whether there was an exception or not another legitimate way of handling exceptions is to create and throw another exceptionpossibly one that specifies the exceptional condition more precisely the following is an example of this approachcatch (arrayindexoutofboundsexception aioobxthrow new shoppinglisttoosmallexce... |
20,764 | implement the sellable interface shown in code fragment we can then define concrete classphotographshown in code fragment that implements the sellable interfaceindicating that we would be willing to sell any of our photograph objectsthis class defines an object that implements each of the methods of the sellable interf... |
20,765 | interface transportable we could then define the class boxeditemshown in code fragment for miscellaneous antiques that we can sellpackand ship thusthe class boxeditem implements the methods of the sellable interface and the transportable interfacewhile also adding specialized methods to set an insured value for boxed s... |
20,766 | well-- class can implement multiple interfaces--which allows us great deal of flexibility when defining classes that should conform to multiple apis forwhile class in java can extend only one other classit can nevertheless implement many interfaces multiple inheritance in interfaces |
20,767 | inheritance in javamultiple inheritance is allowed for interfaces but not for classes the reason for this rule is that the methods of an interface never have bodieswhile methods in class always do thusif java were to allow for multiple inheritance for classesthere could be confusion if class tried to extend from two cl... |
20,768 | java util observerwhich adds an update feature to class that wishes to be notified when certain "observableobjects change state abstract classes and strong typing an abstract class is class that contains empty method declarations (that isdeclarations of methods without bodiesas well as concrete definitions of methods a... |
20,769 | an explicit cast operator we have already discussed (section how conversions and casting work for base types nextwe discuss how they work for reference variables casting and generics in this sectionwe discuss casting among reference variablesas well as techniquecalled genericswhich allow us to avoid explicit casting in... |
20,770 | and are class types and is subclass of and are interface types and is subinterface of is an interface implemented by class in generala narrowing conversion of reference types requires an explicit cast alsothe correctness of narrowing conversion may not be verifiable by the compiler thusits validity should be tested by ... |
20,771 | object cast will be correct namelyit provides an operatorinstanceofthat allows us to test whether an object variable is referring to an object of certain class (or implementing certain interfacethe syntax for using this operator is object referenceinstanceof reference_typewhere object_reference is an expression that ev... |
20,772 | the method equalto assumes that the argument (declared of type personis also of type student and performs narrowing conversion from type person (an interfaceto type student ( classusing cast the conversion is allowed in this casebecause it is narrowing conversion from class to interface uwhere we have an object taken f... |
20,773 | types allows us to write general kinds of data structures that only make minimal assumptions about the elements they store in code fragment we sketch how to build directory storing pairs of objects implementing the person interface the remove method performs search on the directory contents and removes the specified pe... |
20,774 | way that avoids many explicit casts generic type is type that is not defined at compilation timebut becomes fully specified at run time the generics framework allows us to define class in terms of set of formal type parameterswith could be usedfor exampleto abstract the types of some internal variables of the class ang... |
20,775 | [height [student(ida namesueage ) in the previous examplethe actual type parameter can be an arbitrary type to restrict the type of an actual parameterwe can use an extends clauseas shown belowwhere class personpairdirectorygeneric is defined in terms of generic type parameter ppartially specified by stating that it ex... |
20,776 | code goes here *public findother ( personreturn null/stub for find public void remove ( personp other/remove code goes here *this class should be compared with class personpairdirectory in code fragment given the class abovewe can declare variable referring to an instance of personpairdirectorygenericthat stores pairs ... |
20,777 | pair[ new pair[ ]/rightbut gives warning pair[ new pair[ ]/wrong [ new pair()/this is completely right [ set("dog", )/this and the next statement are right too system out println("first pair is "+ [ getkey()+""+ [ getvalue()) exercises for source code and help with exercisesplease visit java datastructures net reinforc... |
20,778 | class goat extends object and adds an instance variable tail and methods milk(and jump(class pig extends object and adds an instance variable nose and methods eat(and wallow(class horse extends object and adds instance variables height and colorand methods run(and jump(class racer extends horse and adds method race(cla... |
20,779 | variable of type horse if refers to an actual object of type equestriancan it be cast to the class racerwhy or why notr- give an example of java code fragment that performs an array reference that is possibly out of boundsand if it is out of boundsthe program catches that exception and prints the following error messag... |
20,780 | class state extends region state(/null constructor *public void printme(system out println("ship it ")class region extends place region(/null constructor *public void printme(system out println("box it ")class place extends object place(/null constructor *public void printme(system out println("buy it ")what is the out... |
20,781 | java console and determines if they can be used in correct arithmetic formula (in the given order)like " ," ,or " * - write short java program that creates pair class that can store two objects declared as generic types demonstrate this program by creating and printing pair objects that contain five different kinds of ... |
20,782 | write program that consists of three classesaband csuch that extends and extends each class should define an instance variable named " (that iseach has its own variable named xdescribe way for method in to access and set ' version of to given valuewithout changing or ' version - write set of java classes that can simul... |
20,783 | numbers as inputone that is monetary amount charged and the other that is monetary amount given it should then return the number of each kind of bill and coin to give back as change for the difference between the amount given and the amount charged the values assigned to the bills and coins can be based on the monetary... |
20,784 | arrayslinked listsand recursion contents using arrays storing game entries in an array sorting an array java util methods for arrays and random numbers simple cryptography with strings and character arrays |
20,785 | two-dimensional arrays and positional games singly linked lists insertion in singly linked list removing an element in singly linked list doubly linked lists insertion in the middle of doubly linked list removal in the middle of doubly linked list an implementation of doubly linked list |
20,786 | circularly linked lists and linked-list sorting circularly linked lists and duckduckgoose sorting linked list recursion linear recursion binary recursion multiple recursion exercises java datastructures net |
20,787 | using arrays in this sectionwe explore few applications of arrayswhich were introduced in section storing game entries in an array the first application we study is for storing entries in an array--in particularhigh score entries for video game storing entries in arrays is common use for arraysand we could just as easi... |
20,788 | suppose we have some high scores that we want to store in an array named entries the number of scores we want to store could be or so let us use symbolic namemaxentrieswhich represents the number of scores we want to store we must set this variable to specific valueof coursebut by using this variable throughout our cod... |
20,789 | storing references to six gameentry objects in the cells from index to with the rest being null references code fragment class for maintaining set of scores as gameentry objects |
20,790 | representation of the high scores in the entries array this method is quite useful for debugging purposes in this casethe string will be comma-separated listing of the gameentry objects in the entries array we produce this listing with simple for-loopwhich adds comma just before each entry that comes after the first on... |
20,791 | to visualize this insertion processimagine that we store in array entries remote controls representing references to the nonnull gameentry objectslisted left-to-right from the one with highest score to the one with the lowest given the new game entryewe need to figure out where it belongs we start this search at the en... |
20,792 | entryebelongswe add reference to at this position that iscontinuing our visualization of object references as remote controlswe add remote control designed especially for to this location in the entries array (see figure figure adding reference to new gameentry object to the entries array the reference can now be inser... |
20,793 | array are similar to this informal descriptionand are given in java in code fragment note that we use loop to move references out of the way the number of times we perform this loop depends on the number of references we have to move to make room for reference to the new game entry if there are or even just few referen... |
20,794 | suppose some hot shot plays our video game and gets his or her name on our high score list in this casewe might want to have method that lets us remove game entry from the list of high scores thereforelet us consider how we might remove reference to gameentry object from the entries array that islet us consider how we ... |
20,795 | the details for doing the remove operation contain few subtle points the first is thatin order to remove and return the game entry (let' call it eat index in our arraywe must first save in temporary variable we will use this variable to return when we are done removing it the second subtle point is thatin moving refere... |
20,796 | simple neverthelessthey form the basis of techniques that are used repeatedly to build more sophisticated data structures these other structures may be more general than the array structure aboveof courseand often they will have lot more operations that they can perform than just add and remove but studying the concret... |
20,797 | character in the array one character by itself is already sorted then we consider the next character in the array if it is smaller than the firstwe swap them next we consider the third character in the array we swap it leftward until it is in its proper order with the first two characters we then consider the fourth ch... |
20,798 | how to insert the element [iinto the subarray that comes before it it still uses an informal description of moving elements if they are out of orderbut this is not terribly difficult thing to do java description of insertion-sort now we are ready to give java code for this simple version of the insertion-sort algorithm... |
20,799 | color the next element that is being inserted into the sorted part of the array with light blue we also highlight that character on the leftsince it is stored in the cur variable each row corresponds to an iteration of the outer loopand each copy of the array in row corresponds to an iteration of the inner loop each co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.