Reputation: 3
I need to parse numerous strings determining if they are int or double. Here is my current code that works with one. I want to be able to simply use the existing two try/catch to keep code tidy, rather than make one for all strings.
void camTestButton(ActionEvent event) throws IOException, InterruptedException {
String cam01 = Cam0GO1.getText();
String cam02 = Cam0GO2.getText();
String cam03 = Cam0GO3.getText();
String cam11 = Cam1GO1.getText();
String cam12 = Cam1GO2.getText();
String cam13 = Cam1GO3.getText();
try {
int textToInt = Integer.parseInt(cam01);
} catch (NumberFormatException e) {
try {
double textToDouble = Double.parseDouble(cam01);
} catch (NumberFormatException e2) {
}
}
System.out.println(cam01);
}
I now have this working, yet I need to take the results and return to each individual textField?
String cam01 = Cam0GO1.getText();
String cam02 = Cam0GO2.getText();
String cam03 = Cam0GO3.getText();
String cam11 = Cam1GO1.getText();
String cam12 = Cam1GO2.getText();
String cam13 = Cam1GO3.getText();
String[] cams = {cam01, cam02, cam03, cam11, cam12, cam13};
for (String c : cams) {
try {
int textToInt = Integer.parseInt(c);
} catch (NumberFormatException e) {
try {
double textToDouble = Double.parseDouble(c);
} catch (NumberFormatException e2) {
}
}
**System.out.println("Cam0GO01 = " + c.?? etc.);**
}
Upvotes: 0
Views: 109
Reputation: 27966
You will need to return the type you've determined from a method. You could use a String
or define your own enum
or just use the built-in Class
.
private static Class getType(String text) {
try {
Integer.parseInt(text);
return Integer.class;
} catch (NumberFormatException ex1) {
try {
Double.parseDouble(text);
return Double.class;
} catch (NumberFormatException ex2) {
return String.class;
}
}
}
Class cam1class = getType(cam1.getText());
If you want to call this once for all the objects in the array then you could create a map with the result:
Map<String, Class> camTypes = Arrays.stream(camArray)
.map(c -> c.getText())
.collect(Collectors.toMap(Function.identity(), this::getType));
Or if you have a Cam
class with equals
and hashCode
defined you could use that as the key instead of strings:
Map<Cam, Class> camTypes = Arrays.stream(camArray)
.collect(Collectors.toMap(Function.identity(), c -> getType(c.getText())));
Upvotes: 0
Reputation: 174
void camTestButton(ActionEvent event) throws IOException,InterruptedException {
String [] array = {Cam0GO1.getText(), Cam0GO2.getText(), Cam0GO3.getText()};
for (String st : array) {
parseCam(st);
}
}
public void parseCam(String st) {
try {
int textToInt = Integer.parseInt(st);
} catch (NumberFormatException e) {
try {
double textToDouble = Double.parseDouble(st);
} catch (NumberFormatException e2) {}
}
System.out.println(st);
}
Upvotes: 1