I have code which sorts my first array of names alphabetically and then sorts the corresponding marks array so they correct student has the correct marks. The problem I have is a nullPointerException
error. From what I understand this error is due to some of the array elements not being initialised, is there any way that I can still sort the array if some of the indices have not been initialised?
static String[] studentNamesArray = new String[10];
static int[][] studentMarksArray = new int[10][3];
static void sortAlphabetical() {
String nameSwap;
int [] markSwap;
boolean flag = false;
while (!flag) {
flag = true;
for (int i = 0;i < 9;i++) {
if (studentNamesArray[i].compareTo(studentNamesArray[i + 1]) > 0) {
nameSwap = studentNamesArray[i];
studentNamesArray[i] = studentNamesArray[i + 1];
studentNamesArray[i + 1] = nameSwap;
markSwap = studentMarksArray[i];
studentMarksArray[i] = studentMarksArray[i + 1];
studentMarksArray[i + 1]= markSwap;
flag = false;
}
}
}
}
Yes. Instead of
if (studentNamesArray[i].compareTo(studentNamesArray[i + 1]) > 0) {
Try using a ternary, or you could use an if else - this is a ternary.
int compare = (studentNamesArray[i] == null) ? -1 :
studentNamesArray[i].compareTo(studentNamesArray[i + 1]);
if (compare > 0) {
The ternary is equivalent to
int compare;
if (studentNamesArray[i] == null) {
compare = 1;
} else {
compare = studentNamesArray[i].compareTo(studentNamesArray[i + 1]);
}
A more complex if else is left as an exercise to the reader(s).
To get it working I made a global variable to keep check of how many elements have been entered in the array and then modified my code as below:
static void sortAlphabetical() {
String nameSwap;
int [] markSwap;
boolean flag = false;
while (!flag) {
flag = true;
for (int i = 0;i < nameArrayCount-1;i++) {
if (studentNamesArray[i].compareTo(studentNamesArray[i + 1]) > 0) {
nameSwap = studentNamesArray[i];
studentNamesArray[i] = studentNamesArray[i + 1];
studentNamesArray[i + 1] = nameSwap;
markSwap = studentMarksArray[i];
studentMarksArray[i] = studentMarksArray[i + 1];
studentMarksArray[i + 1]= markSwap;
flag = false;
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.