Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition offers the best solutions to textbook problems, helping you prepare for exams and assignments.

Joseph Wilson
Contributor
4.7
43
5 months ago
Preview (16 of 166 Pages)
100%
Purchase to unlock

Page 1

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 1 preview image

Loading page image...

Page 1 of 1Weiss 4thEdition Solutions to Exercises(US Version)Chapter 1 – Primitive Java1.1 Key Concepts and How To Teach ThemThis chapter introduces primitive features of Java found in all languages such as Pascal and C:basic lexical elementsprimitive typesbasic operatorscontrol flowfunctions (known as methods in Java)Students who have had Java already can skip this chapter. I teach the material in the order presented. There islittle tricky material here (this is part of the appeal of Java). Although the text does not mention C or C++, hereare some differences:1.Primitive types have precise ranges. There is no unsigned type. A char is 16 bits.2.Order of evaluation is guaranteed (generally left to right). In particular, the sequence point rule fromC++ is not needed. Thus nonsense such as x++ + x++ has a precise behavior in Java.3.Only the C‐style type conversion is allowed.4.boolean is a primitive type, thus removing many of the common errors in C++, such as if(x=y) ... .5.There is no comma operator, except in for loop expressions.6.Java provides a labeled break statement.7.7. All functions must be class methods.1.2 Solutions to ExercisesIN SHORT1.1Java source files end in.java. Compiled files (containing j‐code or byte‐codes) end in.class.1.2//, which extends to the end of the line and/*and/**, both of which extend to a*/. Comments donot nest.1.3boolean,byte,short,char,int,long,float, anddouble.1.4* multiplies two primitive values, returning the result and not changing its two arguments. *=changes the left‐hand argument to the product of the left‐hand argument and the right‐handargument. The right‐hand argument is unchanged.1.5Both the prefix and postfix increment operators add one to the target variable. The prefix operatoruses the new value of the variable in a larger expression; the postfix operator uses the prior value.1.6Thewhileloop is the most general loop and performs a test at the top of the loop. The body isexecuted zero or more times. Thedoloop is similar, but the test is performed at the bottom of theloop; thus the body is executed at least once. Theforloop is used primarily for counting‐likeiteration and consists of an initialization, test, and update along with the body.1.7breakis used to exit a loop. A labeledbreakexits the loop that is marked with a label.breakisalso used to exit aswitchstatement, rather than stepping through to the next case.1.8Thecontinuestatement is used to advance to the next iteration of the loop.1.9Method overloading allows the reuse of a method name in the same scope as long as the signatures(parameter list types) of the methods differ.

Page 2

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 2 preview image

Loading page image...

Page 3

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 3 preview image

Loading page image...

Page 2 of 21.10In call‐by‐value, the actual arguments are copied into the method’s formal parameters. Thus, changesto the values of the formal parameters do not affect the values of the actual arguments.IN THEORY1.11After line 1,bis 6,cis 9, andais 13. After line 2,bis 7,cis 10, andais 16. After line 3,bis 8,cis 11,andais 18. After line 4,bis 9,cis 12, andais 21.1.12The result istrue. Note that the precedence rules imply that the expression is evaluated as(true&&false)||true.1.13The behavior is different ifstatementscontains acontinuestatement.1.14Because of call‐by‐value,xmust be 0 after the call to methodf. Thus the only possible output is 0.IN PRACTICE1.15An equivalent statement is:while(true)statement1.16This question is harder than it looks because I/O facilities are limited, making it difficult to aligncolumns.publicstaticvoidaddition(){for(inti=0;i<10;i++){for(intj=0;j<10;j++){if(i+j<10)System.out.print("");System.out.print(i+j+"");}System.out.println();}}publicstaticvoidmultiplication(){for(inti=1;i<10;i++){for(intj=1;j<10;j++){if(i*j<10)System.out.print("");System.out.print(j*i+"");}System.out.println();}}1.17The methods are shown below (without a supporting class); we assume that this is placed in a classthat already provides the max method for two parameters.publicstaticintmax(inta,intb,intc)

Page 4

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 4 preview image

Loading page image...

Page 3 of 3{returnmax(max(a,b),c);}publicstaticintmax(inta,intb,intc,intd){returnmax(max(a,b),max(c,d));}1.18The method is below:publicstaticbooleanisLeap(intyear){booleanresult=year%4==0&&(year%100!=0||year%400==0);returnresult;}1.3 Exam Questions1.1Consider the following statements:inta=4;intb=7;b*=a;What are the resulting values ofaandb?a.a is 4, b is 7b.a is 28, b is 7c.a is 4, b is 28d.a is 28, b is 28e.the statement is illegal1.2Consider the following statements:inta=4;intb=7intc=++a+b—;What is the resulting value ofc?a.10b.11c.12d.13e.none of the above1.3Consider the following statements:booleana=false;booleanb=true;booleanc=false;booleand;In which of the following isdevaluated?a.a&&db.b&&d

Page 5

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 5 preview image

Loading page image...

Page 4 of 4c.b||dd.c&&de.All the operations evaluated1.4Which of the following loop constructs guarantee that the body is executed at least once?a.doloopb.forloopc.whileloopd.two of the constructse.all three of the constructs1.5In the method below, which statement about the possible outputs is most correct?publicstaticvoidwhat(){intx=5;f(x);System.out.println(x);}a.0 is a possible outputb.5 is the only possible outputc.any positive integer can be outputd.any integer can be outpute.none of the above are true1.6.If two methods in the same class have the same name, which is true:a.They must have a different number of parametersb.They must have different return typesc.They must have different parameter type listsd.The compiler must generate an error messagee.none of the above1.7Considerthe following statements:inta=5;intb=7;intc,d;c=(b-a)/2*a;d=b+7/a;What are the resulting values ofca.cis 0 anddis 2b.cis 0 anddis 2.4c.cis 5 anddis 8d.cis 5 anddis 2e.none of the above1.8Whichofthe following is true andd?a.A variable must be declared immediately before its first use.b.An identifier may start with any letter or any digit.c._33a is a valid identifier.d.both (a) and (c) are truee.all of the above are true

Page 6

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 6 preview image

Loading page image...

Page 5 of 5Answers to Exam Questions1.C2.C3.B4.A5.B6.C7.C8.C

Page 7

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 7 preview image

Loading page image...

Page 6 of 6Chapter 2 – Reference Types2.1 Key Concepts and How To Teach ThemThis chapter introduces several concepts:referencesstringsarraysexceptionsI/ODepending on the students’ background, some or even this entire chapter could be skipped, but I recommendat least a quick review of the chapter in all circumstances. Students who have not had Java should go throughthe entire chapter slowly because there are fundamental differences between Java objects and objects inother languages.2.1.1 ReferencesExplain the general idea of a reference in the context of a pointer. This is important to do because pointers arefundamental in most other languages. Then discuss the basic operations. Most important is to explain thatobjects must be created via new, what=and==means for references, and parameter passing for referencetypes. Students that have used other languages may be confused with the distinction between call‐by‐reference in a language such as Pascal, C++, or Ada and call‐by‐value applied to reference types in Java.Emphasize that the state of the referenced object can change, but the object being referenced by the actualargument prior to the method call will still be referenced after the method call.2.1.2 StringsExplain the basics of theString; especially that it is not an array of characters. The tricky parts are mixingup==andequals, and remembering that the second parameter tosubStringis the first non‐includedposition.2.1.3 ArraysThe tricky part about arrays are that typically the array must be created vianewand if the array is an array ofObject, then eachObjectin the array must also be created bynew. Also, array copies are shallow.2.1.4 Dynamic ExpansionExplain why we double instead of simply add an extra position. DiscussArrayListas a type that maintainsthe size as well as capacity of an array and automatically increases capacity when needed.2.1.5 ExceptionsDesigning inheritance hierarchies is deferred to Chapter 4 when inheritance is discussed. This section simplydiscusses thetry,catch,finallyblocks, thethrowclause and thethrowslist. Students do not seem tohave difficulty with this material.2.1.6 Input and OutputThis section gives a brief description of I/O (mostly I), and theStringTokenizer. The I/O uses Java 1.1constructs. This accounts for almost all of the updating from Java 1.0. TheStringTokenizeris extremelyimportant for simplifying the parsing of input lines. Without it, life will be difficult.2.2 Solutions To ExercisesIN SHORT2.1Reference values (logically) store the address where an object resides; a primitive value stores thevalue of a primitive variable. As a result, operations such as==have seemingly different meaningsfor reference types and primitive types.2.2The basic operations that can be applied to a reference type are assignment via=, comparison via==and!=, the dot operator, type conversion, andinstanceof.

Page 8

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 8 preview image

Loading page image...

Page 7 of 72.3An array has its size associated with it. AnArrayListhas a capacity in addition to size. Adding anelement to anArrayListwill automatically expand the capacity of the array if needed.2.4Exceptions are thrown by a method. The exception immediately propagates back through the callingsequence until it is handled by a matchingcatchclause, at which point the exception is consideredhandled.2.5Basic string operations includeequalsandcompareToto compare,=to copy,+and+=to performconcatenation,length,charAt, andsubstring.2.6Thenextmethod returns the next token from theScannerobject, while thehasNextmethodreturns atruevalue if there exists a token available to be read on theScanner’s stream.IN THEORY2.7The second statement outputs 5 7, as expected. The first outputs 44, because it used the ASCII valueof ‘ ‘, which is 32.2.8The source code in Figure 2.21 fails to compile as shown. In thefoomethod, the compiler does notpermit the multiple return statements (additionally the method isvoid). If you execute a call to thebarmethod, ajava.lang.ArithmeticExceptionis thrown.IN PRACTICE2.9One possible solution to accomplish this is:importjava.io.*;importjava.util.*;publicclassChecksum{publicstaticvoidmain(String[]args){intchecksum=0;System.out.print("Enterthenameofthefile:");Stringfilename=(newScanner(System.in)).nextLine();ScannerfileScanner=null;try{fileScanner=newScanner(newFile(filename));}catch(IOExceptionioe){System.err.println("IOExceptionthrown.");}while(fileScanner.hasNextLine()){Stringline=fileScanner.nextLine();for(inti=0;i<line.length();i++)checksum+=line.charAt(i);}System.out.println("Filechecksum="+checksum);}}2.10One possible solution to do this is:importjava.util.Scanner;

Page 9

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 9 preview image

Loading page image...

Page 8 of 8importjava.io.FileReader;importjava.io.IOException;publicclassListFiles{publicstaticvoidmain(String[]args){ScannerscanIn=null;if(args.length!=0){for(StringfileName:args){System.out.println("FILE:"+fileName);try{scanIn=newScanner(newFileReader(fileName));listFile(scanIn);}catch(IOExceptione){System.out.println(e);}finally{//Closethestreamif(scanIn!=null)scanIn.close();}}}else{scanIn=newScanner(System.in);listFile(scanIn);//Closethestreamif(scanIn!=null)scanIn.close();}}publicstaticvoidlistFile(ScannerfileIn){while(fileIn.hasNextLine()){StringoneLine=fileIn.nextLine();System.out.println(oneLine);}}}2.11A method to do this is below:publicstaticbooleanisPrefix(Stringstr1,Stringstr2){if(str1.length()>str2.length())returnfalse;

Page 10

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 10 preview image

Loading page image...

Page 9 of 9for(inti=0;i<str1.length();i++)if(str1.charAt(str1.length())!=str2.charAt(str2.length()))returnfalse;returntrue;}2.12A method to do this is below:publicstaticintgetTotalStrLength(String[]theStrings){inttotal=0;for(Strings:theStrings)total+=s.length();returntotal;}2.13The elements in the original array are not copied before it is reinitialized.2.14Methods to accomplish this are below:publicstaticdoublesum(double[]arr){doublesum=0.0d;for(inti=0;i<arr.length;i++)sum+=arr[i];returnsum;}publicstaticdoubleaverage(double[]arr){doublesum=0.0d;for(inti=0;i<arr.length;i++)sum+=arr[i];returnsum/arr.length;}publicstaticdoublemode(double[]arr){java.util.Arrays.sort(arr);intmodeCounter=1;intmaxMode=1;doublemodeValue=arr[0];for(inti=0;i<arr.length-1;i++){if(arr[i]==arr[i+1])modeCounter++;if(modeCounter>maxMode){maxMode=modeCounter;modeValue=arr[i+1];

Page 11

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 11 preview image

Loading page image...

Page 10 of 10modeCounter=1;}}returnmodeValue;}2.15Methods to accomplish this are below:publicstaticdoublesum(double[][]arr){doublesum=0.0d;for(introw=0;row<arr.length;row++)for(intcol=0;col<arr[row].length;col++)sum+=arr[row][col];returnsum;}publicstaticdoubleaverage(double[][]arr){doublesum=0.0d;introw=0,col=0;for(row=0;row<arr.length;row++)for(col=0;col<arr[row].length;col++)sum+=arr[row][col];returnsum/(row*col);}publicstaticdoublemode(double[][]arr){double[]newArr=newdouble[arr.length*arr[0].length];intcounter=0;for(introw=0;row<arr.length;row++)for(intcol=0;col<arr[row].length;col++)newArr[counter++]=arr[row][col];java.util.Arrays.sort(newArr);intmodeCounter=1;intmaxMode=1;doublemodeValue=newArr[0];for(inti=0;i<newArr.length-1;i++){if(newArr[i]==newArr[i+1])modeCounter++;if(modeCounter>maxMode){maxMode=modeCounter;modeValue=newArr[i+1];modeCounter=1;}}returnmodeValue;}

Page 12

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 12 preview image

Loading page image...

Page 11 of 112.16Methods to accomplish this are below:publicstaticvoidreverse(String[]arr){for(inti=0;i<arr.length/2;i++){Stringtemp=arr[arr.length-i-1];arr[arr.length-i-1]=arr[i];arr[i]=temp;}}publicstaticvoidreverse(ArrayList<String>arr){for(inti=0;i<arr.size()/2;i++){Stringtemp=arr.get(arr.size()-i-1);arr.set(arr.size()-i-1,arr.get(i));arr.set(i,temp);}}2.17Methods to accomplish this are below:publicstaticintmin(int[]arr){intcurrentMin=arr[0];for(intvalue:arr)if(value<currentMin)currentMin=value;returncurrentMin;}publicstaticintmin(int[][]arr){intcurrentMin=arr[0][0];for(introw=0;row<arr.length;row++)for(intcol=0;col<arr[row].length;col++)if(arr[row][col]<currentMin)currentMin=arr[row][col];returncurrentMin;}publicstaticStringmin(String[]arr){StringcurrentMin=arr[0];for(Stringvalue:arr)if(value.compareTo(currentMin)<0)currentMin=value;returncurrentMin;}

Page 13

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 13 preview image

Loading page image...

Page 12 of 12publicstaticStringmin(ArrayList<String>arr){StringcurrentMin=arr.get(0);for(Stringvalue:arr)if(value.compareTo(currentMin)<0)currentMin=value;returncurrentMin;}2.18A method to do this is below:publicstaticintrowWithMostZeros(int[][]arr){intresult=0,maxCount=0;for(introw=0;row<arr.length;row++){introwCounter=0;for(intcol=0;col<arr[row].length;col++)if(arr[row][col]==0)rowCounter++;if(rowCounter>maxCount){maxCount=rowCounter;result=row;}}returnresult;}2.19Methods to accomplish this are below:publicstaticbooleanhasDuplicates(int[]arr){booleanresult=false;for(inti=0;i<arr.length-1;i++)for(intj=i+1;j<arr.length;j++)if(arr[i]==arr[j])result=true;returnresult;}publicstaticbooleanhasDuplicates(int[][]arr){double[]newArr=newdouble[arr.length*arr[0].length];intcounter=0;for(introw=0;row<arr.length;row++)for(intcol=0;col<arr[row].length;col++)newArr[counter++]=arr[row][col];java.util.Arrays.sort(newArr);booleanresult=false;for(inti=0;i<newArr.length-1;i++)for(intj=i+1;j<newArr.length;j++)if(newArr[i]==newArr[j])

Page 14

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 14 preview image

Loading page image...

Page 13 of 13result=true;returnresult;}publicstaticbooleanhasDuplicates(String[]arr){booleanresult=false;for(inti=0;i<arr.length-1;i++)for(intj=i+1;j<arr.length;j++)if(arr[i].compareTo(arr[j])==0)result=true;returnresult;}publicstaticbooleanhasDuplicates(ArrayList<String>arr){booleanresult=false;for(inti=0;i<arr.size()-1;i++)for(intj=i+1;j<arr.size();j++)if(arr.get(i).compareTo(arr.get(j))==0)result=true;returnresult;}2.20Methods to accomplish this are below:publicstaticinthowMany(int[]arr,intval){intresult=0;for(inti=0;i<arr.length;i++)if(arr[i]==val)result++;returnresult;}publicstaticinthowMany(int[][]arr,intval){intresult=0;for(inti=0;i<arr.length;i++)for(intj=0;j<arr.length;j++)if(arr[i][j]==val)result++;returnresult;}2.21Methods to accomplish this are below:publicstaticintcountChars(Stringstr,charch){intcounter=0;for(inti=0;i<str.length();i++)if(str.charAt(i)==ch)counter++;

Page 15

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 15 preview image

Loading page image...

Page 14 of 14returncounter;}publicstaticintcountChars(String[]str,charch){intcounter=0;for(intstringNum=0;stringNum<str.length;stringNum++)for(inti=0;i<str[stringNum].length();i++)if(str[stringNum].charAt(i)==ch)counter++;returncounter;}2.22Methods to accomplish this include:publicstaticString[]getLowerCase(String[]arr){String[]results=newString[arr.length];intindex=0;for(Stringvalue:arr)results[index++]=value.toLowerCase();returnresults;}publicstaticvoidmakeLowerCase(String[]arr){intindex=0;for(Stringvalue:arr)arr[index++]=value.toLowerCase();}publicstaticArrayList<String>getLowerCase(ArrayList<String>arr){ArrayList<String>results=newArrayList<String>();for(Stringvalue:arr)results.add(value.toLowerCase());returnresults;}publicstaticvoidmakeLowerCase(ArrayList<String>arr){intindex=0;for(Stringvalue:arr)arr.set(index++,value.toLowerCase());}2.23One solution is:publicstaticbooleanisIncreasing(int[][]arr){booleanincreasing=true;for(introw=0;row<arr.length;row++)

Page 16

Solution Manual for Data Structures and Problem Solving Using Java, 4th Edition - Page 16 preview image

Loading page image...

Page 15 of 15for(intcol=0;col<arr[row].length-1;col++)if(arr[row][col]>arr[row][col+1])increasing=false;returnincreasing;}2.24One possible solution is:publicArrayList<String>startsWith(String[]arr,charch){ArrayList<String>results=newArrayList<String>();for(Stringvalue:arr)if(value.charAt(0)==ch)results.add(value);returnresults;}2.25One possible solution is:publicString[]split(Stringstr){ArrayList<String>list=newArrayList<String>();Scannerscan=newScanner(str);while(scan.hasNext())list.add(scan.next());return((String[])list.toArray());}2.26One possible solution includes:importjava.util.Scanner;importjava.util.NoSuchElementException;classMaxTestA{publicstaticvoidmain(String[]args){Scannerin=newScanner(System.in);intx,y;System.out.println("Enter2ints:");StringinputLine=in.nextLine();String[]inputs=inputLine.split("\\s");x=newInteger(inputs[0]).intValue();y=newInteger(inputs[1]).intValue();System.out.println("Max:"+Math.max(x,y));return;}}2.27Here is one possible solution. For whatever reason, reading directly from the input stream(System.in) and using the specified delimiter would not work (tried on multiple platforms). Wasforced to read the input line as aStringand then use a second scanner on theStringto break itinto tokens using the delimiter.
Preview Mode

This document has 166 pages. Sign in to access the full document!

Study Now!

XY-Copilot AI
Unlimited Access
Secure Payment
Instant Access
24/7 Support
Document Chat

Document Details

Related Documents

View all