【发布时间】:2016-03-06 18:59:26
【问题描述】:
我做了两个类,一个叫Card,一个叫Pack。 Card 类具有以下属性:
private String Name;
private int Magic;
private int Cunning;
private int Courage;
private int Wisdom;
private int Temper;
在 Pack 类中,我创建了一个文件读取器方法,用于读取我 PC 上的文件并将其每一行存储为字符串数组。例如,这是文本的一部分(不是代码):
Pansy_Parkinson
42
21
18
19
9
Dean_Thomas
40
10
35
22
4
My String array[] 将每一行存储为不同的索引。 我想做的,就是把这个String数组转换成Card类型的数组。 它应该在每个索引中存储一张具有 6 个属性的卡片..
所以我想我需要一个方法来转换它,并且我将通过这种方式根据之前的文本获得新的 2D Card 数组:
Card [][] ArrayOfCards = new Card [1][5];
请问您知道我该怎么做吗?
.................................................. ............ ..................................................... ........
非常感谢大家的宝贵帮助! 我尝试了所有代码,它们看起来很棒!但我不知道为什么它在我的主要或方法本身中显示错误..
这是我的 FileReader 类!
import java.io.File;
import java.util.Arrays;
import java.io.*; //To deal with exceptions
import java.util.*;
import java.util.Scanner;
import java.util.ArrayList;
public class ReadFile {
private Scanner x;
private String Path;
public ReadFile (String ThePath){
Path = ThePath;
}
public String[] openFile() throws IOException /*To throw any errors up the line*/
{
FileReader FR = new FileReader(Path);
BufferedReader TextReader = new BufferedReader(FR);
int NoOfLines = readLines();
String[] TextData = new String[NoOfLines];
for (int i = 0; i < NoOfLines; i++)
TextData[i] = TextReader.readLine(); //Accesses the lines of text and stores them in the array
TextReader.close();
return TextData;
}
int readLines() throws IOException //Return the number of lines in the text
{
FileReader FR2 = new FileReader(Path);
BufferedReader BF = new BufferedReader(FR2);
String ALine;
int NoOfLines = 0;
while ((ALine = BF.readLine()) != null)//Read each line of text & stop when a null value's reached
NoOfLines++;
BF.close();
return NoOfLines;
}
}
我刚刚在 main 上读过它,如下所示:
public static void main(String[] args) {
// TODO code application logic here
String FileName = "C:/Users/Anwar/Desktop/Potter.txt"; //Path of the file on my PC
try {
ReadFile File = new ReadFile(FileName);
String[] ArrayLines = File.openFile();
for(int i = 0; i < ArrayLines.length; i++)
System.out.println(ArrayLines[i]);
}
catch (IOException e) /*Defiend object of type IOException*/ {
System.out.println(e.getMessage());
}}
任何人都可以帮助我吗?
【问题讨论】:
-
Card[] ArrayOfCards应该足够了。为什么它必须是二维的?或者List<Card>可能会更好 -
我个人会在
Card类上创建一个静态Parse方法,该方法采用string并返回Card,或者如果string的格式不正确则抛出异常.然后你只需要将代表Card的字符串输入其中。另外我建议使用列表而不是数组。而且我认为你的 Pansy Parkinson 的脾气太低了。 -
为什么不使用序列化方法?
-
我同意@ASh。此外,您的问题中有一个 Java 和一个 c# 标记。您使用哪种语言?
-
@DarrenGourley 我猜是 Java。
someType[][]是多维数组的定义方式,在 C# 中是someType[,]
标签: java arrays type-conversion readfile