1
\$\begingroup\$

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++;
 }
 }
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Nov 8, 2013 at 18:53
\$\endgroup\$
3
  • \$\begingroup\$ Fewer lines of code does not mean that your program is more efficient. \$\endgroup\$ Commented Nov 8, 2013 at 19:00
  • \$\begingroup\$ @Pazis: Whats the distinction? \$\endgroup\$ Commented Nov 8, 2013 at 19:03
  • \$\begingroup\$ @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. \$\endgroup\$ Commented Nov 8, 2013 at 19:12

1 Answer 1

2
\$\begingroup\$

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.

answered Nov 8, 2013 at 19:01
\$\endgroup\$
2
  • \$\begingroup\$ I've never seen split, s.trim, or .isEmpty. Would you mind running through how these functions work? I prefer comprehension to memorization. \$\endgroup\$ Commented Nov 8, 2013 at 19:06
  • \$\begingroup\$ @lukeb28 It will sink in more (requiring less memorization) if you hunt for them in the docs. \$\endgroup\$ Commented Nov 8, 2013 at 19:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.