繁体   English   中英

将字符分配给不是int,string,double等类的数组元素。

[英]assign characters to elements of an array which isnt of the int, string, double, etc. class

因此,我有一个读取文件并将类分配给数组元素的方法。 如何为我要分配给数组的每个类分配一个特殊字符?

该数组属于“ Element”类,具有3个属性( intintchar )和这些类(Fantasma,它是“ Element”的子类)。

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;
}

然后您可以例如使用

Element[][] grid = readFile();
for (Element[] ea : grid) {
    for (Element e : ea)
         System.out.print(e.getChar());
     System.out.println();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM