Results 1 to 5 of 5
- 06-26-2012, 11:39 PM #1
Member
- Join Date
- Jun 2012
- Posts
- 3
- Rep Power
- 0
String array to position integers
Hi there,
I have an array of Strings. For example String[] ary = {"bob", "mary", "ken"}; .
I'd like to write code that -for each String in the String array- makes an integer which is named after the name in that position and gets it's value assigned to the String's position in the String element.
For example: I want to make integers bob=1, mary=2, ken=3.
my code so far is:
for(int i=0 ; i < ary.length ; i++) int ary[i]=i;
which doesn't work of course... help please!~
-
Re: String array to position integers
You could make a parallel int array,
(note that arrays are 0 based, and so this will associate 0 with the first String, not 1).Java Code:int[] intArray = new int[ary.length]; for (int i = 0; i < intArray.length; i++) { intArray[i] = i; }
But this is not an elegant solution as it requires one to always be sure to modify the one array if one modifies the other -- a recipe for future disaster.
Another possible solution is to us a Map<String, Integer> such as that provided by a HashMap<String, Integer> and put the desired int with the String.
Another possible solution is to create a class that holds an int and a String, and then create an array of objects of this class rather than one String array and the Map.Java Code:Map<String, Integer> myMap = new HashMap<String, Integer>(); for (int i = 0; i < ary.length; i++) { myMap.put(ary[i], (i + 1)); }
- 06-27-2012, 12:43 AM #3
Member
- Join Date
- Jun 2012
- Posts
- 3
- Rep Power
- 0
Re: String array to position integers
thanks a lot!
- 06-27-2012, 07:59 AM #4
Banned
- Join Date
- Jun 2012
- Location
- Beijing,China
- Posts
- 34
- Rep Power
- 0
Re: String array to position integers
Did you want to generate some MACRO code like SAS,C?
- 06-28-2012, 08:33 PM #5
Member
- Join Date
- Jun 2012
- Posts
- 3
- Rep Power
- 0
Similar Threads
-
how do you add up integers in an array?
By shazakala in forum New To JavaReplies: 7Last Post: 04-19-2011, 10:32 AM -
getting integers from a string
By sehudson in forum New To JavaReplies: 22Last Post: 02-18-2011, 05:34 AM -
Multiples Integers from a String
By AndrewM16921 in forum New To JavaReplies: 3Last Post: 04-01-2009, 12:00 AM -
get position in string from caret position
By helloworld111 in forum AWT / SwingReplies: 5Last Post: 02-19-2009, 01:36 AM -
how to get the Integers out of a String
By JordashTalon in forum New To JavaReplies: 10Last Post: 01-30-2009, 06:28 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks