patternjavaMinor
Improving some plugin user-input code
Viewed 0 times
userinputpluginsomecodeimproving
Problem
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 insight 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 this any better.
I love to make my code elegant, but I don't see how to do this any better.
String x = (JOptionPane.showInputDialog(". Each parameter 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++;
}
}Solution
-
There is absolutely no need to put parentheses around the first statement (small improvement, but it improves readability). "parameter" is also misspelled (improving readability but in a different way).
-
There is no need to use
-
In the rest of your code it seems like you are reading all the doubles from the String (separated by commas), which can be done much easier like this:
The key here is to use the
There is absolutely no need to put parentheses around the first statement (small improvement, but it improves readability). "parameter" is also misspelled (improving readability but in a different way).
String x = JOptionPane.showInputDialog(". Each parameter should be separated with a ',' and without spaces. (eg. 1,2,3)") + ",";-
There is no need to use
Double[] when you can use double[]. The difference is, simply put, that a Double can be null while a double can not.-
In the rest of your code it seems like you are reading all the doubles from the String (separated by commas), which can be done much easier like this:
String[] splitted = x.split(",");
double[] result = new double[splitted.length];
for (int i = 0; i < splitted.length; i++) {
result[i] = Double.parseDouble(splitted[i]);
}The key here is to use the
split-method on the String, which does most of the work for you. For example, it splits the string "0.37,42,21.4" into a string array with the three elements "0.37", "42" and "21.4". The rest of the code loops through that array and converts from String to double.Code Snippets
String x = JOptionPane.showInputDialog(". Each parameter should be separated with a ',' and without spaces. (eg. 1,2,3)") + ",";String[] splitted = x.split(",");
double[] result = new double[splitted.length];
for (int i = 0; i < splitted.length; i++) {
result[i] = Double.parseDouble(splitted[i]);
}Context
StackExchange Code Review Q#34066, answer score: 3
Revisions (0)
No revisions yet.