Computer science question readWorld should read lines from the Scanner until the
ID: 3588979 • Letter: C
Question
Computer science question
readWorld should read lines from the Scanner until there are no more lines to read. Each line will represent a row in the robot's world. The line is allowed to have whitespace characters (spaces and tabs) and the four characters (r, w, b, t). The total number of (r, w, b, t) characters found should be the same on each line, and this number indicates the number of columns in the robot's world. The input lines should have at least one row and at least one column. There should be exactly one r. If any of these specifications are violated or in is null an IllegalArgumentException should be thrown.
Explanation / Answer
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Readrobot {
public void readWorld(Scanner in) {
List<Character[]> charArrList = new ArrayList<>();
int lineLength = 0;
boolean firstLine = true;
while (in.hasNextLine()) { // check for next line
String text = in.nextLine(); // read next line
if (!firstLine && text.length() != lineLength) {
throw new IllegalArgumentException("Different length line found");
}
else {
firstLine = false;
lineLength = text.length();
}
char[] arr = text.toCharArray();
int countR = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 'r' || arr[i] == 'b' || arr[i] == 'w' || arr[i] == 't') {
if (arr[i] == 'r' && countR == 1) {
throw new IllegalArgumentException("Found more than 1 r");
}
} else {
throw new IllegalArgumentException("Char other than r, b, w, t found");
}
}
}
int size = charArrList.size();
char[][] array = new char[size][lineLength];
for (int i = 0; i < size; i++) {
Character[] temp = charArrList.get(i);
for (int j = 0; j < lineLength; j++) {
array[i][j] = temp[j];
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.