如何将数组传递给java中的方法?

时间:2014-04-24 01:13:28

标签: java arrays methods

以下是我尝试运行的程序:

/**
 * Write a description of class mainGame here.
 * 
 * @author Anthony Parsch
 * @version 0.1.1
 */

//Import what I need to.
import java.io.*;
public class mainGame
{

    /**
     * Constructor for objects of class mainGame
     */
    public static void main(String[] args)
    {
        // initialise instance variables
        int xCoord = 10; //The map's max x coordinate +1
        int yCoord = 10; //The map's max y coordinate +1

        int playerX = 0; //The player's current x coordinate
        int playerY = 0; //The player's current y coordinate

        //Declare the arrays
        String[][] map; //[x][y]The map
        String[][] direc; //[x][y]Which directions that you can go
        String[][] items; //[x][y]Where items are at
        String[] inv; // Holds your inventory.
        int[][] helpInt; //[x][y] All the other stuff in the 

        //Initalize the arrays

        //---The player arrays
        inv = new String[10]; //The player's inventory
        inv[0] = "0";
        inv = addItem(inv, "Blarg");//GET RID OF THIS LATER

        //---The map arrays
        map = new String[xCoord][yCoord]; //Descriptions
        direc = new String[xCoord][yCoord]; //north y++,west x--,south y--,east x++
        items = new String[xCoord][yCoord]; //The items within the world



        //Declare the values of map
        map[0][0] = "You wake up with the feel of cold metal on your back. The only other thing in this room is the door.";
        map[0][1] = "You are now in a hallway with a door behind you and one either side. Forward is a continuation of the hallway.com";


        //Declare the values of direc
        direc[0][0] = "north";
        direc[0][1] = "north, south, east, west";

        print(inv[0]);  //Check that the functions work
        print(findDirec(direc, 0, 0));
    }

    /**
     * Finds and displays the avaliable exits for a coordinate.
     * 
     * @param  map[][]   The map array from which this method pulls the directions from.
     * @param  x         The x value of the map
     * @param  y         The y value of the map
     * @return           The string value of which way you can go
     */
    static String findDirec(String[][] map, int x, int y){
        //Pulls the directions
        String match = map[x][y];

        //Checks Directions
        boolean nor = match.matches("(.*)north(.*)");
        boolean sou = match.matches("(.*)south(.*)");
        boolean wes = match.matches("(.*)west(.*)");
        boolean eas = match.matches("(.*)east(.*)");

        //Displays directions
        String placeHolder = "You can go ";

        if (nor == true){
            placeHolder = placeHolder + "north, ";
        } else if(sou == true) {
            placeHolder = placeHolder + "south, ";
        } else if(wes == true) {
            placeHolder = placeHolder + "west, ";
        } else if(eas == true) {
            placeHolder = placeHolder + "east";
        }

        //---Checks if east is in the string, if not it removes the space and comma
        if (eas == false){
            StringBuffer soo = new StringBuffer(placeHolder);

            soo.delete((placeHolder.length()-3), (placeHolder.length()-1));
            placeHolder = soo.toString();
        }

        //Adds the ending period
        placeHolder = placeHolder + ".";

        //Returns the string
        return placeHolder;
    }

    //Adds an item to an inventory
    static String[] addItem(String inv[], String item){
        int i; //Counter for the for loop, and where to add the item at.
        boolean stop = false;

        for(i=0; stop = true; i++)
        {
            if(inv[i].equals("0"))
            {
                stop = true;
            }
        }
        inv[i] = item;
        return inv;
    }
    static void print(String entry){
        System.out.print(entry);
    }
}

当我尝试通过命令提示符运行它时,我收到此错误:     线程" main"中的例外情况java.lang.NullPointerExcpetion         在mainGame.addItem(mainGame.java:113)         在mainGame.main(mainGame.java:38)

4 个答案:

答案 0 :(得分:2)

当我将其粘贴到文本编辑器中时,第113行只是一个右括号}

然而,在此之前的一行是一个逻辑缺陷,我认为这对你来说真的是第113行。

    for(i=0; stop = true; i++)
    {
        if(inv[i].equals("0"))
        {
            stop = true;
        }
    }

循环的每次迭代都会将true分配给stop,然后测试true是否等于true。退出循环的条件是true等于false时,情况永远不会发生,因此循环会一直持续到发生错误为止。另外,您不想在stopfalse时进行迭代吗?我认为你倒退了。

下一个问题是你的if语句,这可能是NullPointerException来自的地方:

        if(inv[i].equals("0"))
        {
            stop = true;
        }

您假设inv[i]引用了一个对象。你需要空检查。

三项建议:

  1. 切勿使用=进行比较。使用==。由于这是一个布尔值,您甚至可以将其简化为stop
  2. 检查for循环中的长度。
  3. 将“0”与inv [i]进行比较而不是相反,以避免空指针解除引用。
  4. 试试这个:

    boolean stop = false;
    for (int i = 0; i < inv.length && !stop; i++)
    {
        if("0".equals(inv[i])
        {
            stop = true;
        }
    }
    

    另一种选择,这是一个形式问题,就是删除循环变量并明确地突破循环。

    for (int i = 0; i < inv.length; i++)
    {
        if("0".equals(inv[i])
        {
            break;
        }
    }
    

答案 1 :(得分:0)

在你的for循环条件中,你更喜欢哪一个?

stop = true或stop == true

答案 2 :(得分:0)

    inv = new String[10]; //The player's inventory
    inv[0] = "0";
    inv = addItem(inv, "Blarg");//GET RID OF THIS LATER

所以你只需要初始化你的数组的一个索引,但是在这里:

   for(i=0; stop = true; i++)
    {
        if(inv[i].equals("0"))
        {
            stop = true;
        }
    }

.. 你循环遍历所有这些。开玩笑,没有读完整个问题。您仍应阅读我的其余答案,但您获得NPE的原因是因为您的循环条件被破坏了。 (顺便说一下你的for循环条件被破坏了,它应该使用==运算符而不是赋值=运算符来测试等价。)

那么您实际使用该代码的是:

inv = new String[10];

此时你有一个容量为10的新String数组,里面没有值,如下所示:

[null][null][null][null][null][null][null][null][null][null]

    inv[0] = "0";

现在将[0]设置为“0”,所以:

["0"][null][null][null][null][null][null][null][null][null]

然后你的循环尝试访问所有这些空引用,这可能就是你有一个空引用异常的原因。

要修复它,只需将数组中的每个索引位置放到任何非null的位置:

Arrays.fill(inv, "");

我使用Arrays.fill() because it's shorter.

答案 3 :(得分:0)

for(i=0; i<inv.length && !stop; i++)
{
    if(inv[i]!=null && inv[i].equals("0"))
    {
        stop = true;
    }
}