In: Computer Science
Find and correct at least two errors in each of the following segments of code.
a) final int ARRAY_SIZE = 5;
ARRAY_SIZE = 10;
int[] table = new int[ARRAY_SIZE]; for (int x = 0; x <=
ARRAY_SIZE; x++)
table[x] = 99;
b) String[] names = {“Mina” , “George”};
int totalLength = 0;
for (int i = 0; i <= names.length() ; i++)
totalLength += names[i].length;
c) String[] words = “Hello”,“Goodbye”; System.out.println(words.toUpperCase());
d) public class MyClass { private int x;
private double y; public void MyClass (double a, double b) {
x = a;
y = b; }
}
e) public class MyClass { private int x;
private double y; public static void myFuncion(int a, double b) {
x = a;
y = b; }
public static int myFunction(int a, double b) { x = a;
y = b;
return 1; }
}
a)
final int ARRAY_SIZE = 5;
int[] table = new int[ARRAY_SIZE]; for (int x = 0; x <
ARRAY_SIZE; x++)
table[x] = 99;
In the code, we cannot modify the value of a variable declared as final. Also, the loop will iterate to less than the value of ARRAY_SIZE.
b)
String[] names = {"Mina" , "George"};
int totalLength = 0;
for (int i = 0; i < names.length ; i++)
totalLength += names[i].length();
}
In the for loop header, to access the length of the array we use names.length and run the loop to a value less than it.Inside the loop, we get the length of individual string using names[i].length() function.
c) String[] words = {"Hello","Goodbye"};
System.out.println(words[0].toUpperCase());
words will be declared as and array, and a value of words array will be converted to upper case since toUpperCase() method works on string objects.
d)
public class MyClass {
private int x;
private double y;
public MyClass (double a, double b) {
x = a;
y = b; }
}
The constructor does not have a return type in a class.
e)
public class MyClass {
private int x;
private double y;
public void myFuncion(int a, double b) {
x = a;
y = b;
}
public int myFunction(int a, double b) {
x = a;
y = b;
return 1;
}
}
Non-static variables cannot be reference from static context. We just make the methods not static.