• Post Reply Bookmark Topic Watch Topic
  • New Topic

using a string builder in conjunction with an arraylist  RSS feed

 
rick pine
Ranch Hand
Posts: 90
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had a test in my class and was unable to come up with a solution, needless to say my grade will be low. But with that fact aside I still want to know how I could have resolved this...
I needed to create a department arraylist and use a string builder to produce the sentence " representatives from the english department, math department, philosophy department and computer science department were present."  This is the code i have, the output its simply the array list departments. I have no clue how to tackle this. Can i get some suggestions.


 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should stop thinking about the detailed Java language commands and just figure out how to express what you want to do in very general terms first.

You started out well enough but when you got to the end, you kind of lost your focus and tripped up while trying to cross the finish line. You had a list of department names prepared on lines 4-8, that was a great start. On line 10, you created a "work space" where you could start stitching the different parts of the string together. On line 11, you laid out the first part of your "work product." So far so good.

Then, on line 12 you lost your focus. You basically stitched the " and" piece to the first part when you should have stitched in a department name first. Then it's all downhill from there.

You already had an idea of what you wanted your final output to look like: "Representatives from the {#department}, {#department}, ... , and {#department} department were present." where the {#department} parts would be replaced by actual department names from your List of  departments. You can see where all the seams are in that string and where you need to insert specific values. All you have to do is figure out the proper order in which to insert the different parts one after another so that you get a string that matches what you already know you need to get.

Basically, the process would be:

1. put "Representatives from the " in the work space
2. stitch on the first department name
3. stitch on a ", "
4. repeat steps 2 & 3 for all other department names except for the last one
5. stitch on ", and "
6. stitch on the last department name
7. finish off and stitch on the last part of the string
8. Show the whole string that's now all stitched together in the work space



 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The mental metaphor I used for my general description was quilting, where I have a bunch of patches of cloth that I would stitch together to form a pattern. You could choose to use a different mental model. Like words and phrases cut out from newspapers and magazines, your "workspace" would be a piece of paper and instead of "stitching" things to each other, you would glue the separate words and phrases to the piece of paper, like a ransom note from a 1970s movie.
 
rick pine
Ranch Hand
Posts: 90
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. put "Representatives from the " in the work space
2. stitch on the first department name

To accomplish this, dont i need to iterate through the array list and pull the specified position? if i do this it means i need to loop thorough the list, and when i do, i get all the elements out not just the first one, or how else could i stitch an element from the array list to sb? I can also do sb.append(departments.toString()); but this again gives me the whole list.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you use a regular for loop, not the enhanced for loop, you can control exactly how many elements you pull out of your list.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Regular Java for-loop vs enhanced java for-loop
 
rick pine
Ranch Hand
Posts: 90
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is what i worked out, looks pitiful but its getting it done.


System.out.println(sb);


representatives from the english, math, philisophy,

 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's the point of using a loop if you're only going to pull out one element with it? You want to pull out all the elements except the last one.

A table to see what the patterns are will help. Were you not taught how to do this?

indexvaluestring to append
0"english""english, "
1"math""math, "
2"philosophy""philosophy, "
3"computer science""and computer science"

You can clearly see in the table that you need to do the same thing for all but the last element of the list. When you have to do the same thing multiple times, you only need one for loop. You just have to think a little harder (not much harder, really) to figure out where to start and where to end.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am afraid I agree with your opinion of that code. I suggest you turn your computer off and write down on paper how you intend to create that sentence. I had to do that sort of thing recently and it entailed writing words and bits of code on little bits of paper and joining them with sticky tape. As you go through that process, write down where you get the pieces to join, so you will remember the order.
Because most StringBuilder methods are not void, you can string them together:-
myStringBuilder.append(...).insert(0, ...).delete(999).somethingElse(...);
Go through the StringBuilder documentation before you copy any of that code.
 
rick pine
Ranch Hand
Posts: 90
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think im almost there, im only missing the last element. I can do a second for loop and get the last element and modify the output, but i don't think that's the best way.
but this would be a nested for loop correct?

 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. Again, what's the point of using a for loop if you're only interested in one element? Pulling out the last element is done only ONE time. *Calculate* the index of the last element, (it's relative to the size of the list), then GET it out of the list and add it to your StringBuilder. Then add the last part of the string to the StringBuilder and you're done. Only thing left to do is display what's in the StringBuilder.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, you're kind of not making good use of your StringBuilder.  Think of it as your workspace or that piece of paper you're trying to turn into a ransom note.  Why would you display each small piece when you're still in the process of building up the whole note?  You just stick the piece to the note. Remember, "sticking the piece on" translates to append() in Java. "Displaying" translates to System.out.print().  The program could certainly work if you just display pieces as you go but then you're not really making proper use of the StringBuilder, are you?

Put everything in the StringBuilder first.  Your program should have only one System.out.println() statement, at the end when you want to "Display the finished work".
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you call System.out.println() for each part of the string, you're basically doing that thing where people go through a stack of cards to show a message and each card has a part of the whole message written on it. That's not what you were asked to do.

 
rick pine
Ranch Hand
Posts: 90
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
im going to follow the "stop coding advice", i know it seems like an easy task for you guys but im struggling and need to cool off.
 
rick pine
Ranch Hand
Posts: 90
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:No. Again, what's the point of using a for loop if you're only interested in one element? Pulling out the last element is done only ONE time. *Calculate* the index of the last element, (it's relative to the size of the list), then GET it out of the list and add it to your StringBuilder. Then add the last part of the string to the StringBuilder and you're done. Only thing left to do is display what's in the StringBuilder.



So i need to do something n times to the elements on the list, that something its add a comma in between, except for the last element. this is why i used the departments.size()-1 on the first loop. and added a comma, also on this loop im adding the content produced to my sb. On the second loop im only interested on the last element, hence the i = 0 ; i < 1; i++ , with this the loop goes through one time only and pulls out one element on position 3, i grab this element and add it to my sb. now my sb its almost completed, i just need to add one last part " were present", so i append again. then at the end i output the sb tha was built on the "work space".



 
Paul Clapham
Sheriff
Posts: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have this loop whose body is only executed once:



Notice that the body of the loop has nothing to do with the list index, which is "i". So how does that loop differ from



which is only executed once?

You're right to take a break though, so your brain can get rid of that meme-gremlin which is yelling "YOU GOTTA USE LOOPS!"
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
rick pine wrote:So i need to do something n times to the elements on the list, that something its add a comma in between, except for the last element. this is why i used the departments.size()-1 on the first loop. and added a comma, also on this loop im adding the content produced to my sb. ...


You're almost there. Lines 1-6 are good. So are lines 10-11. 

Only lines 7 to 9 left. See what Paul said (which is pretty much what I said before, too, about not needing a loop if all you're going to do is pull out the last element of the list). Furthermore, you don't need to hard-code the last element's index. You already said something about the how you calculated the last index for that first for-loop. The calculation you need to make to get the last element's index is only slightly different.
 
rick pine
Ranch Hand
Posts: 90
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This came to me while watching tv. Its funny how after thinking so long with no answer I get an idea out of nowhere. So you guys kept saying "why use a loop if you only need one element", the thing is, i dint know i could just grab an element from an arraylist without looping it. That was never brought up during class, so all of a sudden i thoutgh:  if i can chain append and grab an individual list element without a loop then its done. So this is what i got.



output:
representatives from the english,  math,  philisophy, and computer science were present
 
Paul Clapham
Sheriff
Posts: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looks like our repeated suggestions managed to percolate through to your thought processes. So that's great.

Now you need to test that code to find the error which is still there. (No, it doesn't involve loops!)
 
rick pine
Ranch Hand
Posts: 90
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i noticed there is a comma after philosophy, is that the error you are referring to?
 
Paul Clapham
Sheriff
Posts: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, it isn't. Are you guaranteed that there will always be exactly four departments to format using that code?
 
Paul Clapham
Sheriff
Posts: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, whether there's supposed to be a comma after the second-to-last entry in a list is the notorious "Oxford Comma" controversy which has led to violence among professional editors so I'm not going to advise about that. Put a comma there if the assignment says to put one there, otherwise don't.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:. . . go through a stack of cards to show a message and each card has a part of the whole message written on it. . . .
You might use that technique to monitor the progress of the adding of Strings and remove the println statements later.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Clapham wrote:. . . "Oxford Comma" . . . violence among professional editors . . .
What's wrong with Oxford commas?
Read the output aloud. Does it say, “representatives from the english,  math,  philisophy,       and computer science [departments] were present,” or, “representatives from the english,  math, philisophyand computer science [departments] were present?”
If you pronounce it the first way, it needs an Oxford comma, and if you pronounce it the second way it doesn't need an Oxford comma. Of course, if as Paul C suggests, the instructions say that 935434539592 marks will be deducted for Oxford commas, then you have the decision made for you.

Were you instructed to use a StringBuilder object? Have a look at this class (new in Java8), which (I am 99.9% sure) uses a StringBuilder behind the scenes.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
rick pine wrote:im going to follow the "stop coding advice", i know it seems like an easy task for you guys but im struggling and need to cool off.
It is only easy for us because we aren't doing it. We all faced things just as difficult for us when we were students. The stop coding advice was given because coding is an effective way to make a hard task really difficult.
 
Liutauras Vilda
Sheriff
Posts: 4927
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you take some rest, think about 'if' statement, it might can be a useful thing, which basically gives an ability to do something when you reach a certain point during iteration. For example 'if index is of element...'

example 1
example 2
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:We all faced things just as difficult for us when we were students.

Ain't that the truth. My first machine problem (that's what we called programming assignments) ever was to generate the first N numbers of the Fibonnaci series using a for loop. It took me about two hours to figure out the algorithm. Of course, I didn't have the luxury of having a computer handy. This was back in the mid-80s and we had all of two hours per week in the computer lab at school to actually type in our code and test/debug our programs. That meant a lot of coding on paper and tracing by hand. I guess that was actually a good thing because most of us soon started to get really good at thinking like a compiler.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a potential cheat with a StringBuilder and Oxford commas. You can go back after the event and remove the last comma.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's not really a cheat although I know how it might seem like it is. It's a good way to avoid a repetitive check for the last item inside the loop.
 
rick pine
Ranch Hand
Posts: 90
Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thank you all for your responses and helping me think this through.
I would like some advice if you guys dont mind. For this particular problem i was never told that i could pull out an element from a list without having to iterate though it, that is why i kept doing for loops every time i wanted to pull out a word to stitch it to my sb.
And this has happened often in class, im going to use another loop as example: I was thought how to use a nested for loop to create patterns, like a square , or a rectangle. But then the homework was to create said rectangle but with the perimeter only. So there i was seating at the tutor center having to ask them to explain to me how i could accomplish this daunting task. I feel like while in class im presented with a tool box and handed a carpenter hammer, but i know there is other tools in there that could be useful to get the job done. Then Im asked to put a nail on the wall, but i dont have a nail, so i must look in that tool box and find the nail but not just any nail, a specific one that fits the situation.
I dont know if that makes sense, i guess the question is, how can i turn that carpenter hammer into a jackhammer?, i feel like im confined to the material learned in class, i have browsed the web looking for examples related to what im learning but every time i browse the terms "java", "programming", "examples" im bombarded with content that doesnt even apply to my interest. I really want to become a god programmer but every time i hit a wall i feel deterred and feel like changing my major from Cs to History , talk about contrast.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It differs from one person to the next. You say you want to become a good programmer. If you really want that, then you have to learn to do what good programmers do. You have to learn how to think like good programmers think.

How do you become a good baseball player, or piano player, or artist, or carpenter? Practice, right? Lots of it. And study. Even more of that. To some extent, there's also aptitude and innate talent. Not everybody can grow up to be a LeBron James. But you don't have to be LBJ to play a decent game of hoops either.

My advice has always been to study principles. Know why you do things certain ways when you're programming. Learn how to organize your thoughts and attack a problem systematically. Musashi, Japan's legendary swordsman wrote in his Book of Five Rings: "To become overly attached to one weapon is as bad as not knowing it sufficiently well."  That's what happened with you and the tools you've been given. Don't let the tools be the limitation. Your imagination and creativity is the only real limitation to what you can do with the tools that are available to you. Ok, so that's not really true if you only have a hammer. But then again, I've seen a hammer being used to demonstrate principles of physics and center of mass: https://www.youtube.com/watch?v=NpMSB4FwgtU - so again, there's no telling what someone's imagination can come up with.

Here are the principles you can start with, even if you don't know much about the mechanics of the Java language: Simplicity. Always strive for simplicity. And Clarity. A clean code (organized, small, focused).  Choose good names. Good names makes your code clear and understandable. Bad names mislead both the reader and the writer of the code. That's where bugs come from.  You may think that the advice to choose good names is trivial. "Really? That's the best advice you have, choose good names?"  This is what some of the best programmers in the world say about good names: https://martinfowler.com/bliki/TwoHardThings.html -- Rob Pike, co-creator of the Go programming language, who works at Google, had three items on his list of hard things in programming. Guess what the hardest one was. Yup, you got it: Names.

Sometimes the simplest things are the hardest things to master. If you start with those early and get lots of practice in them, then maybe someday you can claim to be a not-so-bad programmer, maybe even enough to say your a good programmer.

Good luck.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!