如何将文件中的数据插入到对象中

huangapple go评论73阅读模式
英文:

How to insert data from files into objects

问题

需要一些帮助,我有一个 4x4 的矩阵,展示了一座山,在 "Mountain.txt" 文件中有山区的高度:

1 1 1 1
1 2 3 1
1 2 2 1
1 1 1 1

还有一个名为 "Rocks.txt" 的文件,其中包含每个区域的岩石类型:

stone stone stone stone
stone sand sand stone
stone sand sand sand
sand sand sand sand

公共类 "Mountain":

public class Mountain {
    int height;
    String typeRock;
    
    public Mountain(int height, String typeRock) {
        this.height = height;
        this.typeRock = typeRock;
    }
}

我应该如何从这两个不同的文件中读取数据,并创建相应的对象,就像这样:

Mountain zone00 = new Mountain(1, "stone");
Mountain zone01 = new Mountain(1, "stone");
Mountain zone11 = new Mountain(2, "sand");
// 以此类推...
英文:

I need some help, I've got a matrix 4x4 that shows a mountain, in the Mountain.txt there are the heights of mountain zones:

 1 1 1 1        
 1 2 3 1     
 1 2 2 1           
 1 1 1 1  

And the file Rocks.txt that has a type or rock for each zone:

stone stone stone stone
stone sand sand stone
stone sand sand sand
sand sand sand sand

Public class Mountain {       
int height;       
String typeRock;  
public Mountain (int height, String typeRock) {
this.height = height;
this.typeRock = typeRock;
};
}

How do I read that data from 2 different files and to make objects with it, like

Mountain zone00 = new Mountain(1, stone);
Mountain zone01 = new Mountain(1, stone);
Mountain zone11 = new Mountain(2, sand);

And so on...

答案1

得分: 1

以下是翻译好的内容:

从目录中加载文件可以像这样完成:

public String loadFile(String path) {
    StringBuilder builder = new StringBuilder();
    
    try {
        BufferedReader br = new BufferedReader(new FileReader(path));
        String line;
        while((line = br.readLine()) != null) {
            builder.append(line + "\n");
        }
        
        br.close();
    } catch(IOException e ) {
        e.printStackTrace();
    }
    
    return builder.toString();
}

你现在可以使用这个方法将两个文件加载到字符串中:

String mountainData = loadFile("Mountain.txt");
String rockData = loadFile("Rocks.txt");

然后你可以分割这些字符串:

String[] mountainsTokens = mountainData.split("\\s+");
String[] rockTokens = rockData.split("\\s+");

之后你只需要创建你的山脉。为此,你需要遍历矩阵的每个元素(这里大小似乎是4):

Mountain[][] zones = new Mountain[4][4];
for(int y = 0; y < 4; y++) {
    for(int x = 0; x < 4; x++) {
        mountains[y][x] = new Mountain(Integer.parseInt(mountainData[x + y * 4]), rockData[x + y * 4]);
    }
}

为了实现这一点,你需要将一维内容转换为二维内容(x+y*4)。此外,你需要使用Integer.parseInt()将字符串转换为整数。你可能还需要使用try-catch进行异常处理。顺便说一下,我绝对会像上面那样将山脉保存在一个二维数组中。这会使一切变得更容易(而不是写zone00,你可以写zones[0][0])。

希望这能有所帮助。

英文:

Loading a file from a directory could be done like so:

public String loadFile(String path) {
	StringBuilder builder = new StringBuilder();
	
	try {
		BufferedReader br = new BufferedReader(new FileReader(path));
		String line;
		while((line = br.readLine()) != null) {
			builder.append(line + &quot;\n&quot;);
		}
		
		br.close();
	} catch(IOException e ) {
		e.printStackTrace();
	}
	
	return builder.toString();
}

You could know use this method to load both files into strings:

String mountainData = loadFile(&quot;Mountain.txt&quot;);
String rockData = loadFile(&quot;Rpcks.txt&quot;);

You could now split these Strings:

String[] mountainsTokens = mountainData.split(&quot;\\s+&quot;);
String[] rockTokens = rockData.split(&quot;\\s+&quot;);

After that you just need to create your mountains. Therefore you go through each element of your matrix (the size seems to be 4 here):

Mountain[][] zones = new Mountain[4][4];
for(int y = 0; y &lt; 4; y++) {
	for(int x = 0; x &lt; 4; x++) {
		mountains[y][x] = new Mountain(Integer.parseInt(mountainData[x + y * 4]), rockData[x + y * 4]);
	}
}

For that you have to convert something one-dimensional into something two dimensional (x+y*4) Furthermore, you have to convert the String into an int using Integer.parseInt(). You might have to surround with try-catch too.
Btw, I would definetivly save the mountains in a two dimensional arry like above. This makes everything much easier (instead of zone00 you write zones[0][0]).

I hoped that helped.

答案2

得分: 0

public Mountain[][] read(String mountains, String rocks) throws IOException {
    Reader br1 = Files.newBufferedReader(new File(mountains).toPath());
    Reader br2 = Files.newBufferedReader(new File(rocks).toPath());
    Scanner scan1 = new Scanner(br1);
    Scanner scan2 = new Scanner(br2);

    final int rows = /* The number of rows read from input file */;
    final int columns = /* The number of columns read from input file */;

    Mountain[][] mountainArr = new Mountain[rows][columns];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            int mountainHeight = scan1.nextInt();
            String rock = scan2.next();
            mountainArr[i][j] = new Mountain(mountainHeight, rock);
        }
    }
    scan1.close();
    scan2.close();
    return mountainArr;
}

public static class Mountain {
    public Mountain(int height, String rockType) {
    }
}
英文:

You simply open and read two files at a time.

Btw you have a bit of a problem in that the size of your input is hard coded. Instead of assuming that the data is a 4 x 4 array of input, you should add the rows and columns to the input file and read those first. This allows your program to handle any sized data.

This code has not been tested, caveat emptor.

   public Mountain[][] read( String mountains, String rocks ) throws IOException {
      Reader br1 = Files.newBufferedReader( new File( mountains ).toPath() );
      Reader br2 = Files.newBufferedReader( new File( rocks ).toPath() );
      Scanner scan1 = new Scanner( br1 );
      Scanner scan2 = new Scanner( br2 );
      
      final int rows = 4;  // shouldn&#39;t hard code these
      final int columns = 4;
      
      Mountain[][] mountainArr  = new Mountain[rows][columns];
      
      for( int i = 0; i &lt; rows; i++ ) {
         for( int j = 0; j &lt; columns; j++ ) {
            int mountainHeight = scan1.nextInt();
            String rock = scan2.next();
            mountainArr[i][j] = new Mountain( mountainHeight, rock );
         }
         
      }
      scan1.close();
      scan2.close();
      return mountainArr;
   }
   
   public static class Mountain {
      public Mountain( int height, String rockType ) {
      }
   }

huangapple
  • 本文由 发表于 2020年4月7日 02:57:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/61067015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定