Integer.parseInt("42") turns text into an int, Double.parseDouble("1.5") into a double, and String.valueOf(42) or "" + 42 go the other way. Text that is not a number makes parseInt throw a NumberFormatException, which ends the program unless something catches it.
Catching is try { ... } catch (NumberFormatException e) { ... }: the code in try runs, and if it throws that exception, the catch block runs instead of the program stopping. The exceptions module covers this properly; for now it is the tool that makes parsing user input safe.
int n;
try {
n = Integer.parseInt(text.trim());
} catch (NumberFormatException e) {
n = 0;
}Your task
Write static int safeParse(String text, int fallback) returning the number in the text (surrounding spaces allowed) or the fallback when it is not a whole number, static double average(String[] numbers) returning the mean of the texts that parse as doubles (ignoring the ones that do not; 0 when none do), and static String percent(int part, int whole) returning the whole-number percentage with a percent sign (percent(1, 3) is "33%").
Hint 1
try { return Integer.parseInt(text.trim()); } catch (NumberFormatException e) { return fallback; }
Hint 2
average: count and sum the ones that parse inside a try, catch NumberFormatException per element. percent: 100 * part / whole with ints, then + "%".
Show the solution
public class Main {
static int safeParse(String text, int fallback) {
try {
return Integer.parseInt(text.trim());
} catch (NumberFormatException e) {
return fallback;
}
}
static double average(String[] numbers) {
double sum = 0;
int count = 0;
for (String n : numbers) {
try {
sum += Double.parseDouble(n);
count++;
} catch (NumberFormatException e) {
// skip it
}
}
return count == 0 ? 0 : sum / count;
}
static String percent(int part, int whole) {
return 100 * part / whole + "%";
}
public static void main(String[] args) {
System.out.println(safeParse(" 42 ", 0) + " " + safeParse("x", 7) + " " + percent(1, 3));
}
}