[英]How to scan a 2d array?
我正在嘗試讀取文件並將數據填充到二維數組中。 但是在掃描過程中,當我將數據分配到我的MazePoint[][]
數組中時。 它給出以下錯誤消息。
Type mismatch: cannot convert from int to MazePoint
代碼塊:
public MazePoint[][] readMaze(String fileToRead) throws IOException
{
FileInputStream fileByteStream = null; // File input stream
Scanner inFS= null; // Scanner object
fileByteStream = new FileInputStream(fileToRead);
inFS= new Scanner(fileByteStream);
int size = inFS.nextInt();
MazePoint[][] maze = new MazePoint[size][size];
while(inFS.hasNext()) {
for (int row = 0; row < size; row++) {
for (int column = 0; column < size; column++) {
maze[row][column] = inFS.nextInt();
}
}
}
return maze;
}
謝謝
MazePoint 是一種新型的對象(類)。 因此,您不能在那里分配 integer。 但這是可能的。
getter
和setter
添加一個新的value
屬性。class MazePoint {
private int value;
// ... other things here
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
// ... other things
}
public MazePoint[][] readMaze(String fileToRead) throws Exception
{
FileInputStream fileByteStream = new FileInputStream(fileToRead);; // File input stream
Scanner inFS= new Scanner(fileByteStream); // Scanner object
int size = inFS.nextInt();
MazePoint[][] mazePoints = new MazePoint[size][size];
while(inFS.hasNext()) {
for (int row = 0; row < size; row++) {
for (int column = 0; column < size; column++) {
mazePoints[row][column] = new MazePoint();
mazePoints[row][column].setValue(inFS.nextInt());
}
}
}
return mazePoints;
}
完成(演示)項目:
import java.io.FileInputStream;
import java.util.Scanner;
public class Maze {
public static void main(String[] args) throws Exception {
Maze maze = new Maze();
MazePoint[][] mazePoints = maze.readMaze("twoDarray.txt");
maze.print(mazePoints);
}
public MazePoint[][] readMaze(String fileToRead) throws Exception
{
FileInputStream fileByteStream = new FileInputStream(fileToRead);; // File input stream
Scanner inFS= new Scanner(fileByteStream);// Scanner object
int size = inFS.nextInt();
MazePoint[][] mazePoints = new MazePoint[size][size];
while(inFS.hasNext()) {
for (int row = 0; row < size; row++) {
for (int column = 0; column < size; column++) {
mazePoints[row][column] = new MazePoint();
mazePoints[row][column].setValue(inFS.nextInt());
}
}
}
return mazePoints;
}
public void print( MazePoint[][] mazePoints) {
int size = mazePoints.length;
for (int row = 0; row < size; row++) {
for (int column = 0; column < size; column++) {
System.out.print(mazePoints[row][column].getValue() + " ");
}
System.out.println();
}
}
}
class MazePoint {
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
輸入文件twoDarray.txt
:
2 1 2 3 4
Output:
1 2
3 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.