Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I made this nice bit of code that I can insert into any of my projects requiring user input. It seems quite long for what it does and I would love some incite as to how I can do this more efficiently i.e. fewer lines of code.

I love to make my code elegant, but I don't see how to do it any better.

    String x = (JOptionPane.showInputDialog(". Each patamater should be separated with a ',' and without spaces. (eg. 1,2,3)") + ",");
    int w = 0, a = 0, y = -1;
    for(int i = 0; i < x.length(); i++)
    {
        if(x.charAt(i) == ',')
        {
            w++;
        }
    }
    Double[] z = new Double[w];
    for(int i = 0; i < x.length(); i++)
    {
        if(x.charAt(i) == ',')
        {
            z[a] = Double.parseDouble(x.substring((y + 1), i));
            y = i;
            a++;
        }
    }
share|improve this question

migrated from stackoverflow.com Nov 17 '13 at 5:33

This question came from our site for professional and enthusiast programmers.

    
Thanks. I'll re-ask this over there! –  lukeb28 Nov 8 '13 at 18:58
    
Fewer lines of code does not mean that your program is more efficient. –  Pazis Nov 8 '13 at 19:00
    
@Pazis: Whats the distinction? –  lukeb28 Nov 8 '13 at 19:03
    
@lukeb28 Calling a function like orderEveryDogInTheWorld(); will take more time than calling int x = 0; and x = x + 1;, even though the second example is two lines. –  sdasdadas Nov 8 '13 at 19:12

1 Answer 1

up vote 1 down vote accepted

I suggest next way:

    String x = (JOptionPane.showInputDialog(". Each patamater should be separated with a ',' and without spaces. (eg. 1,2,3)") + ",");
    String[] split = x.split(",");
    Double[] z = new Double[split.length];
    int i = 0;
    for (String s : split) {
        if(s.trim().isEmpty()){
            continue;
        }
        try {
            z[i++] = Double.valueOf(s.trim());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

1)split() instead of loop for ','

2)validate spaces

read more about String class and it's functions.

share|improve this answer
    
I've never seen split, s.trim, or .isEmpty. Would you mind running through how these functions work? I prefer comprehension to memorization. –  lukeb28 Nov 8 '13 at 19:06
    
@lukeb28 It will sink in more (requiring less memorization) if you hunt for them in the docs. –  sdasdadas Nov 8 '13 at 19:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.