What is the best way to get a list of input entered by the user and put them in an array or arraylist so that you can do calculations such as adding all the numbers or multiplying them. for example:
Enter numbers to add:
| CLick to add |
I tried using JTextArea but each number wasn't a separate entity since it seems that getText() captures all the text instead of 1 per line. Here is how i tried to do it
That just gives me an error. And when i display the array it shows that instead of each number being an object, there is just one object that has the values "2 3 4 5" and each number starts with a new line, which looks like this:
So is there a correct way of doing this?
A quick and (extremely) dirty way would be to first ask the user how many numbers s/he would like to enter, create an array of this size, and use a for loop to prompt with Input Dialogs. There's surely a much better way, though.
John Danek wrote:A quick and (extremely) dirty way would be to first ask the user how many numbers s/he would like to enter, create an array of this size, and use a for loop to prompt with Input Dialogs. There's surely a much better way, though.
"and (extremely) dirty way" made me lol. That's an interesting way of handling this, so kudos for that! But yeah,i need a more subtle way of doing it : P
You could have 2 JButtons --> + and = When you click +, a new JTextField opens up so that the user can enter a number. The user is restricted to a fixed number of inputs.
When you click =, a new JTextField with the sum is displayed.
Ok, that is a really good method, but i want the user to input as many numbers as they would like. I figured how to parse the string so that if the user enters: 2 3 4 5 into JTextArea then it would parse it using split method of String. Sure enough i was able to sum up the numbers. However when the user enters numbers in a list format like :
then i can't use the same split regex. Now i need to know how to split that : (
I just found out this splitting thing is not very flexible : ( for example if the user puts 2 spaces between each line then the program breaks. Also if the user puts multiple spaces between numbers the code breaks. Also what if the user wants to input numbers on the same line and then start a new set of numbers on a different line?! Is there a way to enable the user to input numbers however they would please and be able to parse that somehow?
if you're using a gui, and you have a small-ish range of numbers e.g. lotto numbers,
a simple way is to add an array of JToggleButtons to a GridLayout JPanel, then, when finished,
iterate the array looking for the button numbers where isSelected() returns true
Yes i ended up doing just that. I used "\\s" and try/catch to get rid of any strings. Now Users can input whatever they want. I was wondering however, if that's really secure, since sometimes you hear exploits caused by string parsing, or some crazy input. Is the try/catch method of doing this safe?