tags:

views:

225

answers:

4

I want to convert a string of 5 numbers separated by commas into integers and store them into an array.

// person class
public class Person {
    private String Name;
    private char sex;
    private String score;
    private int[] grades = new int[5];
    private String newName;
    public Person()   // CONSTRUCTOR
    {

    }

    public void fixName()
    {
        String lower = Name.toLowerCase();
        int a = Name.indexOf(" ",0);
        String first = lower.substring(0, a);
        String last = lower.substring(a+1);
        char f = first.charAt(0);
        char l = last.charAt(0);
        f = Character.toUpperCase(f);
        l = Character.toUpperCase(l);
        String newname = "" + l + last.substring(1) + " " + f + first.substring(1);
    } 
    public void fixScore()
    {
        int b = score.indexOf(",", 0);
        int i = Integer.parseInt(b);
        String[] b = score.split(",", 5);

        System.out.print(b);
    }
}
+3  A: 
  1. Mark your question as "Homework"
  2. Split your string using comma as a delimiter.
  3. Extract each int from the string using ParseInt
  4. Add these ints to your array.
Alex
i understand that but i dont understand how to code them
shep
@shep: you need a good grounding in the Java language and base libraries first. Start with the [Java Tutorials](http://download.oracle.com/javase/tutorial/).
Michael Petrotta
I suggest you read the documentation then. You know the functions involded (Split, ParseInt) and you know the general algorithm. Now go ahead, try to find out how to call each function, what the parameters are, what you will get as result and how to write a simple program that employs all this. If in doubt, consult the documentation and try out a single feature first, i.e. try to split a string, or try to convert a single string to a number.
Jim Brissom
This would be a +1 minus the first bullet point.
T.J. Crowder
I don't mind taking a reputation hit from offended passers-by, in the interest of properly-tagged questions.
Alex
-1 for you first bullet point. Such remarks are hardly helpful.
0xA3
@Alex: The point is that you don't know it's homework. By all means ask, even suggest, but sorry the above is just rude. The guy (or at least the account) is brand new to SO. Let's try not to be jerks.
T.J. Crowder
@Alex: Tagging [homework] adds nothing to the question—in particular, it doesn't help anyone answer better than we already can. If you want to get the OP to write better questions, there are *much* better places to focus their attention.
Roger Pate
@Roger Pate: Yeah, tags add nothing; let's remove them altogether! This is a 2-day old question by someone who has never accepted an answer. Thanks for the -1; you must be proud.
Alex
@Alex: Tags which reflect the *poster's intention* rather than the *question's content* add nothing (and several have been completely removed recently). Your answer is not useful by stressing this as its first point: check how that corresponds to the downvote button's tooltip.
Roger Pate
@Roger Pate: Unfortunately, at this time, the tooltip does not state 'I subjectively feel part of this answer is not useful.' rendering your rhetoric flawed. Still, you are entitled to your opinion -- just as you are entitled to resurrect questions with -4 rating, not even bothering to suggest an answer yourself. I realize now I am dealing with the Robin Hood of Reputation. You have the last word; this conversation is over.
Alex
+3  A: 

Assuming you have:

String data = "1, 23, 456, 789";

...then use String#split to get individual strings for each number, create an int[] array of the same length as the resulting array, loop through the resulting array using String#trim to trim each entry and Integer#parseInt to parse them. It will end up looking something like this (untested):

String[] parts;
int results[];
int index;

parts = data.split(",");
results = new int[parts.length];
for (index = 0; index < parts.length; ++index) {
    results[index] = Integer.parseInt(parts[index].trim());
}

Naturally there are some things not handled in the above, like for instance what to do if you have two commas in a row and parts[index].trim() is therefore blank.

T.J. Crowder
String[] b = score.split(",", 5); Would this be on the right track for the split command
shep
Why not write directly "int[] results = new int[parts.length];"? And why not put the "int index" declaration directly in the for statement?
luiscubal
@shep: Yes, *if* you want to fail if the user supplies more than five. Because `"1,2,3,4,5,6,7".split(",", 5)` would give an array containing the strings `1`, `2`, `3`, `4`, and `5,6,7` -- which I can't believe is really what you want.
T.J. Crowder
the user is not supplying any it is being read from a data file and there are 5 numbers in the file
shep
@luiscubal: Because I don't believe in combining declarations with code (I know most people don't have a problem with it), and in fact shouldn't have compromised to the extent I did when dashing it off. Updated.
T.J. Crowder
@shep: What, data files have never been miswritten? ;-)
T.J. Crowder
Would the downvoter like to provide some helpful feedback?
T.J. Crowder
Why the downvote?
0xA3
+1  A: 

stating the obvious:

String input = "1,2, 4,  10    ,20";

String[] parts = input.split(",");
int[] numbers = new int[parts.length];

for(int i = 0; i < parts.length; i++)
    numbers[i] = Integer.parseInt(parts[i].trim());

return numbers;
pstanton
Gosh that looks familiar. ;-)
T.J. Crowder
when i run this i get weird outputs like [I@5bd6fbb3
shep
@shep: The above doesn't have any output at all. From the looks of what you quoted in your comment, I think it's probably an issue with how you outputted it rather than pstanton's code (or mine, which is nearly identical).
T.J. Crowder
@shep: Can you edit your question and show us what your code looks like? And how do you output the results?
0xA3
@shep: From your code it looks as if you are trying to output the string array directly. You have to loop over the array and write out every entry separately to get the output you want.
0xA3
@T.J. Crowder i typed this out at the same time you did (your edit) and imo is tidier ;) ;)
pstanton
+2  A: 

It's really easy to do in Java... First you need to define some interfaces:

public interface ArrayConverter<I,O> {
    O chop (I input);
}

public interface ArrayTransmogrifier<I,O> {
    O convert (I input);
}

Then you need some concrete implementations:

public class CommaStringToArrayConverter implements ArrayConverter<String,String[]> {

    public String[] chop(String input) {
       return input.split(",");
    }
}

public class StringToIntTransmogrifier implements ArrayTransmogrifier<String[], int[]>{

    public int[] convert(String[] input) {
        int[] ret = new int[input.length];

        for (int i = 0; i < input.length; i++) {
            ret[i] = Integer.parseInt(input[i]);
        }

        return ret;
    }

}

Now, you need some factories to create them. I'd recommend using a IOC container, but that is probably over your head at this point, so we will do a simple abstract factory:

public class ArrayConverterFactory {
    public ArrayConverter GetConverter(String type) {

        if (type.equals("CommmaStringToArrayConverter"))
            return new CommaStringToArrayConverter();

        return null;
    }
}


public class ArrayTransmogrifierFactory {
   public ArrayTransmogrifier GetTransmogrifier(String type) {

        if (type.equals("StringArrayToIntArray"))
            return new StringToIntTransmogrifier();

        return null;
    }
}

And with all that done, it is very simple to do the conversion:

public static void main(String[] args) {

   String inputString = "5,4,3,2,1";

   ArrayConverterFactory factory1 = new ArrayConverterFactory();
   ArrayConverter converter = factory1.GetConverter("CommmaStringToArrayConverter");

   String[] splitString = (String[])converter.chop(inputString);

   ArrayTransmogrifierFactory factory2 = new ArrayTransmogrifierFactory();
   ArrayTransmogrifier transmogrifier = factory2.GetTransmogrifier("StringArrayToIntArray");

   int[] results = (int[])transmogrifier.convert(splitString);

}
FlySwat
Damnit, you guys closed the question while I was typing this.
FlySwat
You know, it might be dangerous to let this be the top-most question considering this is a newbie question and this code could actually end up somewhere in the real world if some reader doesn't get the joke...
luiscubal
OMG. I wish I could say I'd never done something like the above. I wish... (And to anyone reading: Take luiscubal's point: This answer is a *joke*. A well-crafted satirical one...right down to the fact that it doesn't actually generate any output for all the work it goes to.)
T.J. Crowder
You forgot to use a dependency injection framework! Bad! Do it again! ;-)
slomojo