Java 将字符分配给数组中不属于int、string、double等类的元素
所以我有一个方法,它读取一个文件并将类分配给数组的元素。如何为数组中的每个类指定一个特殊字符 数组是具有3个属性int、int、char的class元素 还有那些类Fantasma,它是元素的一个子类Java 将字符分配给数组中不属于int、string、double等类的元素,java,Java,所以我有一个方法,它读取一个文件并将类分配给数组的元素。如何为数组中的每个类指定一个特殊字符 数组是具有3个属性int、int、char的class元素 还有那些类Fantasma,它是元素的一个子类 public void ReadFile() throws FileNotFoundException { Scanner scan = new Scanner(new File("inicio.txt")); while (scan.hasNext()) {
public void ReadFile() throws FileNotFoundException
{
Scanner scan = new Scanner(new File("inicio.txt"));
while (scan.hasNext())
{
String line = scan.next();
if (line.equals("Pared"))
{
int i = scan.nextInt();
int j = scan.nextInt();
_mundo = new Pared[i][j];
}
else if (line.equals("Fantasma"))
{
int i = scan.nextInt();
int j = scan.nextInt();
_mundo = new Fantasma[i][j];
}
}
}
像你的_mundo那样更新全局变量不是一种好的风格。您应该让您的方法返回一个数组 我不知道为什么要将I/j信息复制为数组中的位置和元素构造函数的参数。这样做更有意义:
// untested!
abstract class Element {
private char character;
public char getChar() {
return character;
}
Element(char c) {
character = c;
}
}
class Fantasma extends Element {
Fantasma() {
super('F');
}
}
class Pared extends Element {
Pared() {
super('P');
}
}
class Vacio extends Element {
Vacio() {
super(' ');
}
}
public Element[][] readFile() throws FileNotFoundException {
Scanner scan = new Scanner(new File("inicio.txt"));
Element[][] res = new Element[10][10]; // insert your dimensions here
while (scan.hasNext()) {
String line = scan.next();
if (line.equals("Pared") || line.equals("Fantasma")) {
int i = scan.nextInt();
int j = scan.nextInt();
if(line.equals("Pared"))
res[i][j] = new Pared();
else
res[i][j] = new Fantasma();
}
}
// add spaces so we're not left with any null references
for (int i = 0; i < res.length; i++)
for (int j = 0; j < res[i].length; j++)
if (res[i][j] == null)
res[i][j] = new Vacio();
return res;
}
你能再清楚一点你在做什么吗?我读到的是,您试图向数组中添加对象,但在查看代码时,我可能错了。在我看来,你似乎试图调用Pared和Fantasma构造函数,但你使用的语法表明它们是数组。是的,我试图向数组中添加对象,但我真的不知道怎么做,然后我试着在数组的特定位置显示任何字符,我添加了一个对象。你能给我一点帮助吗?我可以假设_mundo是你的数组,我和j代表数组中你想要放置新的Pared或Fantasma的位置吗?是的,你假设正确。而那些写着_mundo=new Fantasma[i][j]或Pared的句子,正如你所说的,是错误的。我想应该是新帕雷迪,对吗?Pared和Fantasma有2个心房,谢谢!,让我看看我是否能让它工作。但是我有几个问题,我假设getChat方法是一个抽象方法,对吗?那么:代表什么呢?非常感谢你,路易吉,你的回答非常有用,我可以按照我的意愿运行我的程序。非常感谢,不客气。getChar不是抽象的-它只是在一个抽象类上,由子类继承。:是增强for循环查找它的语法,在中发音。
Element[][] grid = readFile();
for (Element[] ea : grid) {
for (Element e : ea)
System.out.print(e.getChar());
System.out.println();
}