I am working on an app. Here’s a small fragment which converts the entered string to a fraction:
JavaScript
x
public int[] fractionalize(String rawFraction1) {
int[] result = {0,0,0};
if (rawFraction1.contains("/") && !rawFraction1.contains(" ")){
//normal fraction
int a = Integer.parseInt(rawFraction1.split("/")[0]);
int b = Integer.parseInt(rawFraction1.split("/")[1]);
result = new int[]{a,b,0};
} else if (rawFraction1.contains("/") && rawFraction1.contains(" ")){
//mixed fraction
int wholeNum = Integer.parseInt(rawFraction1.split(" ")[0]);
int num = Integer.parseInt(rawFraction1.split(" ")[1].split("/")[0]);
int den = Integer.parseInt(rawFraction1.split(" ")[1].split("/")[1]);
result = new int[]{num, den, wholeNum};
} else if (!rawFraction1.contains(" ") && !rawFraction1.contains("/")){
int wholeNum = Integer.parseInt(rawFraction1);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "The number you entered is in an invalid format. Please see the correct format to enter numbers.",Toast.LENGTH_LONG);
toast.show();
}
return result;
}
This works pretty well, provided you enter the number in the correct format. However, if we mess up the format, example, inserted 2 spaces or ‘/’, the app crashes and closes. I want that if the program encounters a problem in this segment, it should show a toast instead and not close.
Is this possible? If yes, how?
Advertisement
Answer
Just surround it with try/catch as easy as:
JavaScript
public int[] fractionalize(String rawFraction1) {
try {
int[] result = {0, 0, 0};
if (rawFraction1.contains("/") && !rawFraction1.contains(" ")) {
//normal fraction
int a = Integer.parseInt(rawFraction1.split("/")[0]);
int b = Integer.parseInt(rawFraction1.split("/")[1]);
result = new int[]{a, b, 0};
} else if (rawFraction1.contains("/") && rawFraction1.contains(" ")) {
//mixed fraction
int wholeNum = Integer.parseInt(rawFraction1.split(" ")[0]);
int num = Integer.parseInt(rawFraction1.split(" ")[1].split("/")[0]);
int den = Integer.parseInt(rawFraction1.split(" ")[1].split("/")[1]);
result = new int[]{num, den, wholeNum};
} else if (!rawFraction1.contains(" ") && !rawFraction1.contains("/")) {
int wholeNum = Integer.parseInt(rawFraction1);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "The number you entered is in an invalid format. Please see the correct format to enter numbers.", Toast.LENGTH_LONG);
toast.show();
}
return result;
} catch (Exception e) {
e.printStackTrace();
Toast toast = Toast.makeText(getApplicationContext(), "Invalid Input.", Toast.LENGTH_LONG);
toast.show();
}
return null;
}