gpt4 book ai didi

java - 如何确定文本文件中的藏宝图(行和列)有多大?

转载 作者:行者123 更新时间:2023-12-01 11:47:19 24 4
gpt4 key购买 nike

我想知道如何计算出传递的文本文件的行和列。假设文本文件如下所示:

X...................
....................
....................
....................
....................
....................
....................
....................
....................
..X.................

这个文本文件有 10 行和 20 列,我在如何为我的构造函数获取这些行和列方面遇到了麻烦(不要担心“X”符号)。我只是想知道如何从文本文件中获取行和列/想知道如何计算出 map 有多大。

我需要有关代码中第二个构造函数的帮助:

import java.util.Scanner;   // Required to get input
import java.io.File; // Required to get input from files



// A 2D treasure map which stores locations of treasures in an array
// of coordinates
public class TreasureMap{
int rows, cols; // How big is the treasure map
Coord [] treasureLocations; // The locations of treasures

Scanner kbd = new Scanner(System.in);
// Prompt the user for info on the treasure map and then create it

public TreasureMap(){

int numberOfTreasures = 0;
System.out.println("Enter map size (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
System.out.println("Enter number of treasures (1 int): ");
numberOfTreasures = kbd.nextInt();

treasureLocations = new Coord[numberOfTreasures];

for (int i = 0; i < numberOfTreasures; i++)
{
System.out.println("Enter treasure " + i + " location (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
treasureLocations[i] = new Coord(rows, cols);
}
}



// Read the string representation of a map from a file

public TreasureMap(String fileName) throws Exception{

Scanner data = new Scanner(new File(fileName));
int counter = 0;
while(data.hasNextLine())
{
counter++;
}


}



// true if there is treasure at the given (r,c) coordinates, false
// otherwise
// This method does not require modification
public boolean treasureAt(int r, int c){
for(int i=0; i<treasureLocations.length; i++){
Coord coord = treasureLocations[i];
if(coord.row == r && coord.col == c){
return true;
}
}
return false;
}

// Create a string representation of the treasure map

public String toString(){
String [][] map = new String[this.rows][this.cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
map[i][j] = ".";
}
}
for(int i=0; i<treasureLocations.length; i++){
Coord c = treasureLocations[i];
map[c.row][c.col] = "X";
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
sb.append(map[i][j]);
}
sb.append("\n");
}
return sb.toString();
}

}

最佳答案

以下是一些可用于从文件中读取行的代码:

File file = new File(fileName);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
int rows = 0;
int cols = 0;
while ((line = br.readLine()) != null) {
// process the line
rows++;
cols = line.length(); // always the size of the last line in the file
}
}
br.close();

关于java - 如何确定文本文件中的藏宝图(行和列)有多大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29055548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com