14 Replies - 6857 Views - Last Post: 18 March 2013 - 08:10 PM Rate Topic: -----

#1 arilion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 17-March 13

ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 08:04 PM

I am writing a program that is based off of gridworld. To put a long story short I am getting the following error and don't know how this is possible!
File: C:\Users\Ari\Dropbox\BugWarz\BugWarz\GUIController.java  [line: 255]
Error: Type mismatch: cannot convert from BattleActor to BattleActor

BTW this happens whenever anything involves the BattleActor class
(This project is do tomorrow and I really need help! :helpsmilie: I can attach some of the code if it is necessary.)\
here is the code which invokes this error...
BattleActor occupant = world.getGrid().get(loc);

...and here is the grid's method for get()...
public BattleActor get(Location loc)
    {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc
                    + " is not valid");
        return occupantArray[loc.getRow()][loc.getCol()]; // unavoidable warning
    }


And finally, here is the code for BattleActor which extends Actor.
import java.awt.Color;

public class BattleActor extends Actor
{
  private Team team;
  private int teamNumber;
  private Grid<BattleActor> grid;
  private Location location;
  
  public BattleActor(Team t){
    team = t;
    teamNumber = team.getTeamNumber();
    grid = team.getWorld().getGrid();
    location = getLocation();
  }
  
  public BattleWorld getWorld(){
    return team.getWorld();
  }

  public Team getTeam(){
      return team;
  }
  
  public int getTeamNumber(){
    return teamNumber;
  }
  
  public void changeColor(double f){
    Color c = getColor();
    int red = (int) (c.getRed() * (1 + f));
    int green = (int) (c.getGreen() * (1 + f));
    int blue = (int) (c.getBlue() * (1 + f));
    
    setColor(new Color(red, green, blue));
  }
  
  public void putSelfInGrid(Grid<BattleActor> gr, Location loc)
    {
        if (grid != null)
            throw new IllegalStateException(
                    "This actor is already contained in a grid.");

        BattleActor actor = gr.get(loc);
        if (actor != null)
            actor.removeSelfFromGrid();
        gr.put(loc, this);
        grid = gr;
        location = loc;
    }
  
  public void removeSelfFromGrid()
    {
        if (grid == null)
            throw new IllegalStateException(
                    "This actor is not contained in a grid.");
        if (grid.get(location) != this)
            throw new IllegalStateException(
                    "The grid contains a different actor at location "
                            + location + ".");

        grid.remove(location);
        grid = null;
        location = null;
    }
  
    public void moveTo(Location newLocation)
    {
        if (grid == null)
            throw new IllegalStateException("This actor is not in a grid.");
        if (grid.get(location) != this)
            throw new IllegalStateException(
                    "The grid contains a different actor at location "
                            + location + ".");
        if (!grid.isValid(newLocation))
            throw new IllegalArgumentException("Location " + newLocation
                    + " is not valid.");

        if (newLocation.equals(location))
            return;
        grid.remove(location);
        BattleActor other = grid.get(newLocation);
        if (other != null)
            other.removeSelfFromGrid();
        location = newLocation;
        grid.put(location, this);
    }
}

I really appreciated it! Thanks sooo much!

Is This A Good Question/Topic? 0
  • +

Replies To: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

#2 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12324
  • View blog
  • Posts: 45,424
  • Joined: 27-December 08

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 08:11 PM

Is your Grid class different than the standard BoundedGrid or UnboundedGrid? If so, can you post it? Also, can you post your GUIController class?
Was This Post Helpful? 0
  • +
  • -

#3 arilion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 17-March 13

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 08:19 PM

View Postmacosxnerd101, on 18 March 2013 - 03:11 AM, said:

Is your Grid class different than the standard BoundedGrid or UnboundedGrid? If so, can you post it? Also, can you post your GUIController class?

Thank you.
Yes I had to modify the BoundedGrid class below.
import java.util.ArrayList;
public class BoundedGrid<BattleActor> extends AbstractGrid<BattleActor>
{
    private BattleActor[][] occupantArray; // the array storing the grid elements

    public BoundedGrid(int rows, int cols)
    {
        if (rows <= 0)
            throw new IllegalArgumentException("rows <= 0");
        if (cols <= 0)
            throw new IllegalArgumentException("cols <= 0");
        occupantArray = new BattleActor[rows][cols];
    }

    public int getNumRows()
    {
        return occupantArray.length;
    }

    public int getNumCols()
    {
        // Note: according to the constructor precondition, numRows() > 0, so
        // theGrid[0] is non-null.
        return occupantArray[0].length;
    }

    public boolean isValid(Location loc)
    {
        return 0 <= loc.getRow() && loc.getRow() < getNumRows()
                && 0 <= loc.getCol() && loc.getCol() < getNumCols();
    }

    public ArrayList<Location> getOccupiedLocations()
    {
        ArrayList<Location> theLocations = new ArrayList<Location>();

        // Look at all grid locations.
        for (int r = 0; r < getNumRows(); r++)
        {
            for (int c = 0; c < getNumCols(); c++)
            {
                // If there's an object at this location, put it in the array.
                Location loc = new Location(r, c);
                if (get(loc) != null)
                    theLocations.add(loc);
            }
        }

        return theLocations;
    }

    public BattleActor get(Location loc)
    {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc
                    + " is not valid");
        return occupantArray[loc.getRow()][loc.getCol()]; // unavoidable warning
    }

    public BattleActor put(Location loc, BattleActor obj)
    {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc
                    + " is not valid");
        if (obj == null)
            throw new NullPointerException("obj == null");

        // Add the object to the grid.
        BattleActor oldOccupant = get(loc);
        occupantArray[loc.getRow()][loc.getCol()] = obj;
        return oldOccupant;
    }

    public BattleActor remove(Location loc)
    {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc
                    + " is not valid");
        
        // Remove the object from the grid.
        BattleActor r = get(loc);
        occupantArray[loc.getRow()][loc.getCol()] = null;
        return r;
    }
}


I also made major changes to the GUIControler class.
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.Modifier;
import java.util.Comparator;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeSet;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.*;

public class GUIController<BattleActor>
{
  public static final int INDEFINITE = 0, FIXED_STEPS = 1, PROMPT_STEPS = 2;
  
  private static final int MIN_DELAY_MSECS = 10, MAX_DELAY_MSECS = 1000;
  private static final int INITIAL_DELAY = MIN_DELAY_MSECS
    + (MAX_DELAY_MSECS - MIN_DELAY_MSECS) / 2;
  
  private Timer timer;
  private JButton buyButton;
  private JButton turnLeftButton;
  private JButton turnRightButton;
  private JButton moveButton;
  private JButton shootButton;
  private JComponent controlPanel;
  private GridPanel display;
  private WorldFrame<BattleActor> parentFrame;
  private int numStepsToRun, numStepsSoFar;
  private ResourceBundle resources;
  private DisplayMap displayMap;
  private boolean running = true;
  private Set<Class> occupantClasses;
  private BattleWorld world;
  private FighterBug selected;
  private Grid<BattleActor> gr;
  
  /**
   * Creates a new controller tied to the specified display and gui
   * frame.
   * @param parent the frame for the world window
   * @param disp the panel that displays the grid
   * @param displayMap the map for occupant displays
   * @param res the resource bundle for message display
   */
  public GUIController(WorldFrame<BattleActor> parent, GridPanel disp,
                       DisplayMap displayMap, ResourceBundle res)
  {
    resources = res;
    display = disp;
    parentFrame = parent;
    this.displayMap = displayMap;
    makeControls();
    
    occupantClasses = new TreeSet<Class>(new Comparator<Class>()
                                           {
      public int compare(Class a, Class B)/>
      {
        return a.getName().compareTo(b.getName());
      }
    });
    
    BattleWorld world = parentFrame.getWorld();
    gr = world.getGrid();
    for (Location loc : gr.getOccupiedLocations())
      addOccupant(gr.get(loc));
    for (String name : world.getOccupantClasses())
      try
    {
      occupantClasses.add(Class.forName(name));
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
    
    timer = new Timer(INITIAL_DELAY, new ActionListener()
                        {
      public void actionPerformed(ActionEvent evt)
      {
        step();
      }
    });
    
    display.addMouseListener(new MouseAdapter()
                               {
      public void mousePressed(MouseEvent evt)
      {
        Grid<BattleActor> gr = parentFrame.getWorld().getGrid();
        Location loc = display.locationForPoint(evt.getPoint());
        if (loc != null && gr.isValid(loc))
        {
          display.setCurrentLocation(loc);
          locationclicked();
        }
      }
    });
    stop();
  }
  
  /**
   * Advances the world one step.
   */
  public void step()
  {
    parentFrame.getWorld().step();
    parentFrame.repaint();
    if (++numStepsSoFar == numStepsToRun)
      stop();
    for (Location loc : gr.getOccupiedLocations())
      addOccupant(gr.get(loc));
  }
  
  public void stop()
  {
    display.setToolTipsEnabled(true);
    parentFrame.setRunMenuItemsEnabled(true);
    timer.stop();
    running = false;
  }
  
  private void addOccupant(BattleActor occupant)
  {
    Class cl = occupant.getClass();
    do
    {
      if ((cl.getModifiers() & Modifier.ABSTRACT) == 0)
        occupantClasses.add(cl);
      cl = cl.getSuperclass();
    }
    while (cl != Object.class);
  }
  
  public void run()
  {
    display.setToolTipsEnabled(true);
    parentFrame.setRunMenuItemsEnabled(true);
    numStepsSoFar = 0;
    timer.start();
  }
  
  private void makeControls()
  {
    Team team;
    if(world.getTurn()==1)
      team = world.getTeam1();
    else team = world.getTeam2();
    
    controlPanel = new JPanel();
    controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS));
    controlPanel.setBorder(BorderFactory.createEtchedBorder());
    
    buyButton = new JButton(resources.getString("button.gui.buy"));
    turnLeftButton = new JButton(resources.getString("button.gui.turnLeft"));
    turnRightButton = new JButton(resources.getString("button.gui.turnRight"));
    moveButton = new JButton(resources.getString("button.gui.move"));
    shootButton = new JButton(resources.getString("button.gui.shoot"));
    Dimension spacer = new Dimension(5, buyButton.getPreferredSize().height + 10);
    
    controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS));
    controlPanel.setBorder(BorderFactory.createEtchedBorder());
    
    controlPanel.add(Box.createRigidArea(spacer));
    
    controlPanel.add(buyButton);
    controlPanel.add(Box.createRigidArea(spacer));
    controlPanel.add(turnLeftButton);
    controlPanel.add(Box.createRigidArea(spacer));
    controlPanel.add(turnRightButton);
    controlPanel.add(Box.createRigidArea(spacer));
    controlPanel.add(moveButton);
    controlPanel.add(Box.createRigidArea(spacer));
    controlPanel.add(shootButton);
  }
  /**
   * Returns the panel containing the controls.
   * @return the control panel
   */
  public JComponent controlPanel()
  {
    return controlPanel;
  }
  
  /**
   * Callback on mousePressed when editing a grid.
   */
  private void locationclicked()
  {
    BattleWorld world = parentFrame.getWorld();
    Location loc = display.getCurrentLocation();
    if (loc != null && !world.locationclicked(loc) && world.getGrid().get(loc) instanceof FighterBug)
      select((FighterBug) world.getGrid().get(loc));
    parentFrame.repaint();
  }
  
  private void select(FighterBug actor){
    selected.changeColor(-0.2);
    actor.changeColor(0.2);
    selected = actor;
  }
    /**
     * Edits the contents of the current location, by displaying the constructor
     * or method menu.
     */
    public void deleteLocation()
    {
      BattleWorld world = parentFrame.getWorld();
      Location loc = display.getCurrentLocation();
      if (loc != null)
      {
        world.remove(loc);
        parentFrame.repaint();
      }
    }
    /**
     * Edits the contents of the current location, by displaying the constructor
     * or method menu.
     */

    public void editLocation()
    {
        Location loc = display.getCurrentLocation();
        if (loc != null)
        {
            BattleActor occupant = world.getGrid().get(loc);
            if (occupant == null)
            {
                MenuMaker<BattleActor> maker = new MenuMaker<BattleActor>(parentFrame, resources,
                        displayMap);
                JPopupMenu popup = maker.makeConstructorMenu(occupantClasses,
                        loc);
                Point p = display.pointForLocation(loc);
                popup.show(display, p.x, p.y);
            }
            else
            {
                MenuMaker<BattleActor> maker = new MenuMaker<BattleActor>(parentFrame, resources,
                        displayMap);
                JPopupMenu popup = maker.makeMethodMenu(occupant, loc);
                Point p = display.pointForLocation(loc);
                popup.show(display, p.x, p.y);
            }
        }
        parentFrame.repaint();
    }
  }

Thanks! :smile:
Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12324
  • View blog
  • Posts: 45,424
  • Joined: 27-December 08

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 08:29 PM

The line number in the error message doesn't match up to the code you posted.

Just an FYI though. This class declaration public class BoundedGrid<BattleActor> extends AbstractGrid<BattleActor> doesn't enforce that BoundedGrid only contains BattleActors. It's the same as declaring: class MyList<T> extends ArrayList<T>. You are left with a generic class. Hence, you get problems when dealing with generic arrays.

I'd be willing to bet this is the main source of your problems. I would just stick with a standard implementation of Grid, personally.

Also, a stylistic point. You should never throw a NullPointerException. It's not meant to be recovered from, so it will break somewhere. Let it trace through at that point. Checking for null Objects is good, but throwing the Exception defeats the purpose of the check.

Hope this helps some!
Was This Post Helpful? 1
  • +
  • -

#5 arilion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 17-March 13

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 08:34 PM

View Postmacosxnerd101, on 18 March 2013 - 03:29 AM, said:

The line number in the error message doesn't match up to the code you posted.

Just an FYI though. This class declaration public class BoundedGrid<BattleActor> extends AbstractGrid<BattleActor> doesn't enforce that BoundedGrid only contains BattleActors. It's the same as declaring: class MyList<T> extends ArrayList<T>. You are left with a generic class. Hence, you get problems when dealing with generic arrays.

I'd be willing to bet this is the main source of your problems. I would just stick with a standard implementation of Grid, personally.

Also, a stylistic point. You should never throw a NullPointerException. It's not meant to be recovered from, so it will break somewhere. Let it trace through at that point. Checking for null Objects is good, but throwing the Exception defeats the purpose of the check.

Hope this helps some!

So how can I ensure have a Grid of BattleActor so that I can call a method of BattleActor for any given object in the grid? Why doesn't GridWorld run into this problem?
Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12324
  • View blog
  • Posts: 45,424
  • Joined: 27-December 08

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 08:36 PM

Like I said in my last post, I'd stick with a standard implementation of Grid. Just use the existing BoundedGrid class.

The way generics are handled with arrays is with casting. So an Object[] (or Object[][] in your case) is stored. For the mutator methods, the parameter is of type T (the generic type). For the accessor methods, the array is accessed and its element is cast for the return statement.
Was This Post Helpful? 1
  • +
  • -

#7 arilion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 17-March 13

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 08:49 PM

OK, so i thought I had a reason for not doing it that way but Ill give it a try...
It gave me this error
File: C:\Users\Ari\Dropbox\BugWarz\BugWarz\GUIController.java  [line: (no source location)]
Error: Internal compiler error: java.lang.NullPointerException at java.lang.String.<init>(Unknown Source)

Im not very familiar with this type of exception do u know what it means?
Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12324
  • View blog
  • Posts: 45,424
  • Joined: 27-December 08

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 08:50 PM

It means that you didn't initialize an Object properly. The variable is null, which means it does not reference an actual Object in memory.
Was This Post Helpful? 1
  • +
  • -

#9 arilion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 17-March 13

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 08:57 PM

how do I know what to look for if it says "unknown source"
Was This Post Helpful? 0
  • +
  • -

#10 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12324
  • View blog
  • Posts: 45,424
  • Joined: 27-December 08

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 08:58 PM

There should be a stack trace for you to run through.
Was This Post Helpful? 0
  • +
  • -

#11 arilion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 17-March 13

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 09:03 PM

java.lang.NoClassDefFoundError: TeamBase
	at Team.<init>(Team.java:28)
	at BattleWorld.<init>(BattleWorld.java:26)
	at BugWarz.main(BugWarz.java:6)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

TeamBase is a file which I deleted but none of those first three places
at Team.<init>(Team.java:28)
	at BattleWorld.<init>(BattleWorld.java:26)

at BugWarz.main(BugWarz.java:6) even invoke it any more
Was This Post Helpful? 0
  • +
  • -

#12 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12324
  • View blog
  • Posts: 45,424
  • Joined: 27-December 08

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 09:06 PM

It seems you have missed a dependency.
Was This Post Helpful? 0
  • +
  • -

#13 arilion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 17-March 13

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 09:13 PM

View Postmacosxnerd101, on 18 March 2013 - 04:06 AM, said:

It seems you have missed a dependency.

Alright I guess I will have to look some more tomorrow. Thanks!
Was This Post Helpful? 0
  • +
  • -

#14 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12324
  • View blog
  • Posts: 45,424
  • Joined: 27-December 08

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 17 March 2013 - 09:17 PM

Glad I could help some!
Was This Post Helpful? 0
  • +
  • -

#15 arilion   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 17-March 13

Re: ERROR: CANNOT CONVERT FROM FILE OF SAME TYPE?! (how is this possib

Posted 18 March 2013 - 08:10 PM

ok i tried doing it this way and when i compile it says File:
C:\Users\Ari\Dropbox\BugWarz\BugWarz\GUIController.java  [line: (no source location)]
Error: Internal compiler error: java.lang.NullPointerException at java.lang.String.<init>(Unknown Source)


and when i try to run GUIControler it says "Current document is out of sync with the Interactions Pane and should be recompiled!"
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1