Calculate square
# Topic
Array exceptions
# Problem
Calculate Square
You need to implement the calculateSquare
method.
It should output the square of the element by the provided index of an array. In the case when the exception might happen, your program output should be: Exception!
# Hint & Explain
if checking with conditions check if array == null first
Order of conditions in if statement matters!
first check if array is null, then his length, not inversely, or you get error:)
# Solution
# Other solution 1
class FixingExceptions {
public static void calculateSquare(int[] array, int index) {
// write your code here
String result;
/* Important! If "array.length" were before "array==null", it wouldn't work!
You may want to read more about evaluating OR-expressions and AND-expressions */
if (array == null || index < 0 || index >= array.length) {
result = "Exception!";
} else {
result = String.valueOf(array[index] * array[index]);
}
System.out.println(result);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Other solution 2
class FixingExceptions {
public static void calculateSquare(int[] a, int i) {
boolean exception = a == null || i < 0 || i >= a.length;
System.out.print(exception ? "Exception!" : a[i] * a[i]);
}
}
1
2
3
4
5
6
2
3
4
5
6
# Other solution 3
class FixingExceptions {
public static void calculateSquare(int[] array, int index) {
// write your code here
try {
System.out.println((int) Math.pow(array[index], 2));
} catch (Exception e) {
System.out.println("Exception!");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# Error solution 1
class FixingExceptions {
public static void calculateSquare(int[] array, int index) {
// write your code here
// it would be error!!!
if (index >= 0 || index <= array.length - 1 | array != null) {
System.out.println(array[index] * array[index]);
} else {
System.out.println("Exception!");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# Error solution 2
class FixingExceptions {
public static void calculateSquare(int[] array, int index) {
// write your code here
// it would be error too!!!
if (array != null || index >= 0 || index <= array.length - 1) {
System.out.println(array[index] * array[index]);
} else {
System.out.println("Exception!");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
编辑 (opens new window)
上次更新: 2022/09/25, 10:41:23