Reputation: 55
My 2D array is not being assigned values as it should. The method is called here:
public static void inputPair() throws IOException {
System.out.println("Enter symbol which you want to pair letter to:");
char s = 'a';
while (s == 'a') {
try {
s = input.next(".").charAt(0);
} catch (InputMismatchException e) {
System.out.println("Please enter a valid symbol!");
input.next();
}
}
System.out.println("Enter letter which you want to pair symbol to:");
char l = '#';
while (l == '#') {
try {
l = input.next(".").charAt(0);
} catch (InputMismatchException e) {
System.out.println("Please enter a valid letter!");
input.next();
}
if ((s <= 'a') && (s >= 'z')) {
System.out.println("Please enter a valid letter!");
l = '#';
}
}
makePair(s, l);
System.out.println("Pair made!");
}
and the makePair method:
public static void makePair(char s, char l) {
for (int i = 0; i < words.length; i++) {
words[i] = words[i].replace(s, l);
}
try {
pairings[findFree()][0] = Character.toString(l);
pairings[findFree()][1] = Character.toString(s);
} catch (Exception e) {
System.out.println("Please start again!");
System.exit(0);
}
}
This should assign the value of l and s into the 2D array at the first empty cell due to the findFree method:
public static int findFree() {
for (int i = 0; i < pairings.length; i++) {
if (pairings[i][0] == null) {
return i;
}
}
return 27; // Greater than 26
}
However the cell remains having the value of null.
Upvotes: 0
Views: 705
Reputation: 34796
I'm not sure that this is the only problem, but it seems wrong:
pairings[findFree()][0] = Character.toString(l);
pairings[findFree()][1] = Character.toString(s);
findFree()
will find index of an array in the pairings
2D array whose value at index 0 is null
, let's say it's 0.l
will be assigned to [0][0]
findFree()
again - pairings[0]
will not be selected, because it already contains l
(which is not null) at index 0, so the next one will be selected (let's say 1)l
will be assigned to [1][1]
.Thus you will end up with [l][null]
and [null][s]
, instead of the desired [l][s]
(at least I assume that this is the result you want).
To fix it do something like this:
int freeIndex = findFree();
pairings[freeIndex][0] = Character.toString(l);
pairings[freeIndex][1] = Character.toString(s);
Upvotes: 1