Java代写:CSE174_Lab13_Learning_A_New_Class

CSE 174 - Lab 13

Part 1 (8 points): Learning a new class.

1. Study the Customer class:
● For this lab you are to use the Customer class and in order to finish this lab
successfully you need to study this class very carefully, and you will be tested for
that.
● Download theAPI Documentation for Customer Class.
● Start studying the class description first.
● Scroll down and study the constructors.
● After learning about constructors, scroll down again and study the methods. You
can click on each method name to see more details.

1
2
3
★ You should not go any further if there is somethingin this class that you dont
understand.Youcangobackandstudythematerial,talktoyourfriends,oryoucanask
your instructor in case you need help with understanding this class.

2. Using the Customer class:
● In jGRASP create a java file called Lab13.
● DownloadtheCustomer.javafile(DONOTCHANGEANYTHINGINSIDETHIS
FILE) and put it in the same folder as your Lab13.javafile.
● Insidethemainmethod,createafewCustomerobjects,calldifferentmethods
and printthe results. Forinstance: createtwoCustomerobjects,calldifferent
methodsoneachobjectandprinttheresults.Comparetwoobjects,seeifthe
resultisacceptableforyou.Printtheobjectstoseehowtheoutputlookslike.
Now, try to print the object in a different format.

1
2
★ Again, if you have any questions please ask your instructor. You should not go to the
next part of the lab without understanding all details of this class.
  1. Take the quiz 13.1:
    ● Nowit’stimetoevaluateyourunderstandingofthisclass.Pleasegoaheadand
    take the quiz 13.
    

Part 2 (12 points): Array of Objects & Search algorithms

InthisPartofthelabyouaretocreateanarrayofCustomerobjects,andinitializeeach

objectwiththedatafromafile.Thenyouaretowrite 2 methods,oneforlinearsearchand

oneforbinarysearchandlookfordifferentkeystoseewhichsearchmethodcanfindthe

keys faster.

1. Reading data from a file:
● Download the filecustomer_list.txtand put it inthe same folder as your
Lab13.java file.
● Try not toopenthefile,sincethistextfilecontainsmorethanamillionlinesand
could causeyourjGRASPtocrash.Asyoucanseeinthefollowingimage,in
each line there is a nickname and idnumber separated byspace which is
necessary for creating one Customer object:

1
2
3
4
● Nowlet’swritesomecode.Insidethemainmethod(ifyoulikeyoucanwritea
separatemethodforthat,it’suptoyou),writesomecodetoopenthefileand
counthowmanylinesthistextfilehasandprinttheresultsimilartothefollowing
line:
1
(you should not hardcode that number, your code shouldcalculate the number)

2. Creating an array of Customer objects:
● Nowthatyouknowhowmanylinesthetextfilehas,thatmeansyouknowthe
lengthofyourarray.So,goaheadanddefineanarrayofCustomersusingthat
number as the length of your array.
● Youcannotdefineanarraywithoutknowingthelength.Inaddition,afterdefining
one,youcannotchangethelengthofthearraydirectly.Therefore,havingafixed
size list/array is one of the weaknesses of using arrays.
● Afterdefiningthearray,javawillinitializeeachelementofthearraywitha null
value, which means each element inside the array (eachelement is like a
Customervariable)is pointingto nothingand it isreadytopointtoanactual
Customer object.
● Theonly differencebetweenarraysofprimitivetypesandobjectsisthatafter
defininganarrayofobjectsyoushouldassignanobjecttoeachelement.So,it’s
timetoreadfromthefilelinebylineagain,butthistimeforcreatingaCustomer
object from each line and assigning it to each element of the array.
● Reopen your text file again. The file needs to be reopened because inthe
previouspartwealreadywentthroughthefileoncetocounthowmanylinesthe
file has.
Hint: for reopening the file you can create a new Scanner object and
re-assign it into your previous Scanner variable.
● Usingaloop,startreadingfromthefileaslongasthereissomethinginsidethe
file. UsehasNext() methodoverhasNextLine().Keepthatinmindduringeach
iteration you need to read one String and one long value.
● During eachiterationafter readingtwoelementsfroma line(oneString,one
long),usethemtocreateaCustomerobject(youpracticedthatinthePart1of
Lab13),andusethatCustomerobjecttoinitializethecurrentelementofthearray
with.So,thefollowingisthesummaryofwhatyouneedtodoafterdefiningan
array of Customers:

1
2
3
4
5
loop (as long as there is something inside the file) {
Read one string and one long value
Create a new Customer object
arr[i] = The Customer object created in the previous line
}
1
2
3
4
5
● Nowlet’s testyour arraytosee ifyouwereabletoreadfromthefile,create
Customerobjects,andsavetheminsidethearraycorrectly.Printtheelementsat
the indexof 0,10, 1000,1000000,andthe lastelement ofthe array.Before
printingeachobject,printtheindexaswell.So,yourresultsofarshouldlooklike
the following:

3. Writing a linear search method:
● So far,youwereable toreadfrom afileand createalist/arrayofCustomer
objects.
● NowthequestionishowwillyoufindaspecificCustomerobjectbetweenmillions
of elements inside the array?
● Asasolution,let’swriteamethodcalled linearSearch thatacceptsanarrayof
Customerobjects,andoneCustomerobjectasthekeythatneedstobefound
insidethe array.Andif yourecall, thelinearsearch methodshouldreturnan
index.
● Theonlydifferencebetweenthismethodandtheoneinthevideosisthathere
youaredealingwithCustomerobjects.So,everytimeyouneedtocheckeach
elementofthearraywiththegivenkeytoseewhethertheyareequalornot(you
practiced comparing two Customer objects in the Part1 of this lab).
● When you are done with the method, let’s test it to see if it works. Inside the main
method create a Customer object called key using the nickname: “gwstikg” and
id: 100005949
● Call the linearSearch method and give it your array and the key you just created,
and print the result. Add some messages to have your output as following:

1
2
3
4
5
● Now, inside the linearSearch method add a counterto count every time it
compares the Customer objects. Then, before returning the index, print the
number of times that comparison has happened. The goal is to see how many
times elements are compared inside this method. So, you need to count and print
that inside this method. So, change your code to generate an output as below:

4. Writing a binary search method:
Repeat the whole process from the last section this time to write the
binarySearch method. Write a binarySearch method thatgets an array of
Customers and a key, and returns an index. Count how many comparisons
happen inside this method and print it inside this method right before returning
any values.
The question that you need to ask here is whether the array is sorted since the
binary search algorithm only works with sorted lists. The good news here is that
the array is sorted based on id numbers, therefore inside the binarySearch
methodwhere you need to compare the key with thevalue of the middle element
to see if it’s greater or smaller, you only need to compare the idNumbers.
Comment out some of the previous prints and make sure your output matches
the following output:

1
2
3
4
5
● Repeat the process for finding the following Customers (the numbers are long
type):
○ [“mqzhfygjuk”, 6001073675]
○ [“gnv”, 7412760286]
○ [“CSE174”, 1111111111]
1
● After printing the results your output should look like the following:

5. Analyzing the results:

1
2
3
4
5
6
7
8
9
10
11
12
13
● Looking at the first test, you can see the linear search only did one comparison
compared to binary search that did 19 comparisons,meaning if you are looking
for something at the very beginning of the array, using the linear search could be
a better option over the binary search.
● For the second test, you can see the fast result of binary search by doing only 17
comparisons compared to the linear search which did 598734 comparisons.
● In the third test, you can see each method returns a different index, and that is
because there are duplicate keys inside the file. Since each algorithm searches
through the array differently, each algorithm finds the key at a different index.
● The last test shows the worst case scenario where the key is not in the list. The
linear search has to check all n or 1004718 elementsto realize that the key is not
in the list, while the binary search did only log2(n) or 20comparisons to get the
same result.

6. Submit your Code on canvas:

● If your code generated the last results as shown above, you are ready to submit
your work on canvas.
● There are two tests: one that tests your linear search, and one for testing your
binary search.
Rubric

1
Criteria Full Credit Partial Credit No Credit
1
2
Successful
submission via Code
1
2
3
4
5
6
A fully successful
submission to CODE
that passes all of the
required tests will
earn full credit.
8 Points
1
2
Complete each
test.
1
4 Points
1
2
3
4
if your submission is
not accepted by
code, you will
receive no credit.
1
0 Points
1
2
3
4
Writing comments for
the class and linear
and binary search
methods
1
2
3
4
5
6
7
Writing comments for the
class and the linear and
binary search methods.
explaining the purpose,
parameters, and the return
type will earn full credit.
1.5 Point
1
2
3
Complete
comments for
each part.
1
0.5 Point
1
2
3
4
5
Not writing
comments or
incomplete
comments receive
no credit.
1
0 Points
1
2
3
4
Correct Style If your submission
has 0 style errors you
will earn full credit.
2.5 Point
1
2
3
4
If there are any style
errors present, you
will receive no credit.
0 Points