• Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList & Combo Box  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've just created my first Java program, a password creator program. It works just fine with no problems, but now I'm going back through the code to find ways to optimize it. The program uses a gui that is composed of combo boxes so that the user can select the type of password, the password length, and the number of passwords desired, and I am trying to optimize the code associated with the password length combo box.

The way it works: I have an arraylist that contains a list of random characters, and depending on the number selected in the password length combo box, determines the number of positions I need to get a random character from the arraylist, concatenate them together, and assign them to a string variable.

I feel as if there's a cleaner way to accomplish this. I was thinking that I could parse an integer from the combo box and use it in a for loop to create the password length, but I cannot figure a way to do this. If anyone has any insight on this, please help. I would greatly appreciate it!

See code below.


 
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeffrey,
Welcome to CodeRanch! I've added code tags to make the code easier to read.

Your instinct is correct that there is a cleaner way of doing this. Have you learned about loops yet?

If you look at the JavaDoc, there is a method on the Integer class that converts a string to a number. That lets you write a loop from 0 or 1 to that number adding the relevant index from characterHolder on each time through the loop.

Rewriting it this way makes the snippet you posted about 5 lines long. I'm not posting the revised snippet so you can take a stab at it. Do post back if you have questions though. Or once you have the updated code so you can help others new to Java/programming!
 
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome again

As well as Jeanne’s changes, I have added line breaks. The compiler doesn’t care how long or short a line is, but a screen can only display a certain line length without awkward scrolling.
Do you think a combo box is a suitable component for choosing numbers? Maybe a spinner or a slider would work better. You can find more about them here. Use ctrl-F.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!