\$\begingroup\$
\$\endgroup\$
3
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
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.
-
\$\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\$lukeb28– lukeb282013年11月08日 19:06:06 +00:00Commented 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\$sdasdadas– sdasdadas2013年11月08日 19:11:34 +00:00Commented Nov 8, 2013 at 19:11
lang-java
orderEveryDogInTheWorld();
will take more time than callingint x = 0;
andx = x + 1;
, even though the second example is two lines. \$\endgroup\$