I am supposed to convert my 2nd line from my .txt file filled with 15 X's and O's and print it out onto a 2D array in java.
Here is my 1D array on my .txt file.
XOXOX
XOOXX
XXXOO
XXOOO
XXXXO
OOOOX
XOOXX
OOXXO
OXOXO
OXXXO
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.print("Enter the input filename ");
String inputFile = in.next();
Scanner inFile = new Scanner(new File(inputFile));
String line=inFile.nextLine();
line.toUpperCase();
String array[] = line.split("X");
System.out.println(array[0]+ " " + array [1]);
String arrayE1 = array[0];
String arrayE2 = array[1];
Integer.parseInt(arrayE1);
Integer.parseInt(arrayE2);
String line2 = inFile.next();
System.out.println(line2);
char [][] MovieTheater = new char [Integer.parseInt(arrayE1)][Integer.parseInt(arrayE2)];
int k = 0;
for (int i = 0; i < Integer.parseInt(arrayE1); i++) {
for (int j = 0; i < Integer.parseInt(arrayE2); j++) {
MovieTheater[i][j] = line2.charAt(k++);
}
System.out.println("");
}
inFile.close();
}
You can use Files.lines()
to read all lines in the file and String.toCharArray()
to get all the chars from each line:
try (Stream<String> lines = Files.lines(Paths.get(inputFile))) {
char[][] movieTheater = lines
.map(String::toCharArray)
.toArray(char[][]::new);
System.out.println(Arrays.deepToString(movieTheater));
}
The result will be this 2D array:
[
[X, O, X, O, X], [X, O, O, X, X],
[X, X, X, O, O], [X, X, O, O, O],
[X, X, X, X, O], [O, O, O, O, X],
[X, O, O, X, X], [O, O, X, X, O],
[O, X, O, X, O], [O, X, X, X, O]
]
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.