简体   繁体   中英

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

So I have a method that reads a file and assigns classes to elements of an array. How do I assign a special character for each class that I am giving to my array?

The array is of the class "Element" that has 3 attributes ( int , int , char ) and those classes (Fantasma, which is a subclass of "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];
        }
    }
}

It's not good style to update global variables like your _mundo . You should have your method return an array.

I'm not sure why you would want to duplicate the i / j information as locations in your array and as arguments to your element constructor. It would make more sense to do something like this:

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

Then you can for example print it out with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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