First of all, thank you for coming and taking the time to help with the problem.
I have spent countless hours searching all over and still have not found a working solution to my problem: How do you use the scanner to scan individual characters from each line of string in a .txt file into a 2D array of unknown dimensions?
Problem 1: How do you determine the number of columns of an unknown .txt file? Or is there a better method of determining the size of an unknown 2d array with the .nextInt() method and how?
Problem 2: How do you print out a 2d array without weird [@#$^@^^ errors on the console?
Problem 3: How do you get the scanner to print any character that it reads from the .txt file onto the console (with 2d arrays (yes I know, arrays of arrays))?
Here's my incomplete code to give you an idea of the problem:
import java.util.Scanner;
import java.io.File;
public class LifeGrid {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(new File("seed.txt"));
int numberOfRows = 0, columns = 0;
while (scanner.hasNextLine()) {
scanner.nextLine();
numberOfRows++;
}
char[][] cells = new char[numberOfRows][columns];
String line = scanner.nextLine(); // Error here
for (int i = 0; i < numberOfRows; i++) {
for(int j = 0; j < columns; j++) {
if (line.charAt(i) == '*') {
cells[i][j] = 1;
System.out.println(cells[i][j]);
}
}
}
System.out.println(numberOfRows);
System.out.println(columns);
}
}
A scanner once used can't be reset to the starting position. You have to create a new instance again. I've modified your code to possibly achieve what you're trying to do -
import java.util.Scanner;
import java.io.File;
public class LifeGrid {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(new File("seed.txt"));
int numberOfRows = 0, columns = 0;
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
if( s.length() > columns ) columns = s.length();
numberOfRows++;
}
System.out.println(numberOfRows);
System.out.println(columns);
char[][] cells = new char[numberOfRows][columns+1];
scanner = new Scanner(new File("seed.txt"));
for (int i = 0; i < numberOfRows; i++) {
String line = scanner.nextLine();
System.out.println("Line="+line+", length="+line.length());
for(int j = 0; j <= line.length(); j++) {
if( j == line.length() ) {
cells[i][j] = (char)-1;
break;
}
cells[i][j] = line.charAt(j);
}
}
System.out.println(numberOfRows);
System.out.println(columns);
for (int i = 0; i < numberOfRows; i++) {
for(int j = 0; j <= columns; j++) {
if( cells[i][j] == (char)-1 ) break;
System.out.println("cells["+i+"]["+j+"] = "+cells[i][j]);
}
}
}
}
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.