简体   繁体   English

将.indexOf()与ArrayList一起使用<String>

[英]Using .indexOf() with ArrayList<String>

I am attempting to create a battleship game using Java. 我正在尝试使用Java创建战舰游戏。 The actual game works, but I ran into a surprising (for me) issue along the way. 实际的游戏可行,但是在此过程中我遇到了一个令人惊讶的问题(对我而言)。 The code below generates a random location from a grid of 49 values that a user has to guess from. 下面的代码从49个值的网格中生成一个随机位置,用户必须从中猜测。 As a debugging tool, I figured I would print out the index of the ArrayList's number value, but I got a -1 (found out that means a value not found). 作为调试工具,我认为我会打印出ArrayList的数字值的索引,但是我得到了-1(发现这意味着找不到值)。 Why didn't it return a number, considering my math was right? 考虑到我的数学正确,为什么它没有返回数字?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class GameHelper 
{
String alphabet = "abcdefg";
private int gridLength=7;
private int gridSize=49;
private int [] grid = new int [gridSize];
private int comCount=0;

public String getUserInput(String prompt)
{
    String inputLine=null;
    System.out.println(prompt);

    try
    {
        BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
        inputLine=is.readLine();
        if (inputLine.equals(null))
        {
            return null;
        }
    }

    catch(IOException e)
    {
        System.out.println("Buffered Reader Failure");
    }
    return inputLine;
}


public ArrayList <String> placeDotCom (int size)
{
    ArrayList <String> alphaCells = new ArrayList <String>();

    String temp=null;
    int [] coords=new int[size];
    int attempts=0;
    boolean success=false;
    int location=0;

    comCount++;
    int incr=1;
    if((comCount%2)==1)
    {
        incr=gridLength;
    }

    while (!success & attempts++ < 200)
    {
        location = (int)(Math.random()*gridSize);
        int x=0;
        success=true;
        while (success && x < size)
        {
            if (grid[location] ==0)
            {
                coords[x++]=location;
                location+=incr;
                if(location >= gridSize)
                {
                    success = false;
                }
                if(x>0 && (location % gridLength ==0))
                {
                    success = false;
                }
            }
                else
                {
                    System.out.println("used" + location);
                    success=false;
                }
            }
        }


        int x=0;
        int row=0;
        int column=0;

        while(x < size)
        {
            grid[coords[x]] = 1;
            row = (int)(coords[x]/gridLength);
            column = coords[x] % gridLength;
            temp = String.valueOf(alphabet.charAt(column));

            alphaCells.add(temp.concat(Integer.toString(row)));
            x++;
        }
        System.out.println("coord "+x+" = "+alphaCells.get(x-1));
        return alphaCells;
    }

} 

My attempted call: 我的未接电话:

for (DotCom dcset : dc)
{
ArrayList <String> newLocation = helper.placeDotCom(3);
dcset.setLocationCells(newLocation);
System.out.println(newLocation.indexOf(1));
}

I figured this was the only relevant code. 我认为这是唯一相关的代码。 If you would like me to post more, please tell me. 如果您希望我发布更多信息,请告诉我。 This is my first time posting, and I'm not sure I asked this question correctly. 这是我第一次发帖,我不确定我是否正确地问了这个问题。 Is this too vague? 这太含糊吗?

From the documentation of ArrayList#indexOf(Object o) 来自ArrayList#indexOf(Object o)的文档

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. 返回指定元素在此列表中首次出现的索引;如果此列表不包含该元素,则返回-1 More formally, returns the lowest index i such that Objects.equals(o, get(i)) , or -1 if there is no such index. 更正式地,返回最低索引i这样Objects.equals(o, get(i))-1如果没有这样的索引)。

Notice that the method expects an Object as parameter (this has historical reasons, it stems from the dark ages where no generics existed in Java and all containers used Object ). 请注意,该方法将Object作为参数(这有历史原因,它源于Java时代不存在泛型且所有容器都使用Object的黑暗时代)。

Now, you declared ArrayList <String> newLocation and call .indexOf(1) on this object. 现在,您声明了ArrayList <String> newLocation并在此对象上调用.indexOf(1) The passed int -value gets autoboxed into an Integer . 传递的int值将自动装箱Integer Since your newLocation -list contains only String s, the passed Integer cannot be found in the list. 由于newLocation -list仅包含String ,因此在列表中找不到传递的Integer Thus, it returns a -1 . 因此,它返回-1


A remark on your code: As I wrote in my comment , inputLine.equals(null) will either return false (if inputLine is not null ) or throw a NullPointerException (if inputLine is null ). 关于您的代码的备注:正如我在评论中所写, inputLine.equals(null)将返回false (如果inputLine不为null )或抛出NullPointerException (如果inputLinenull )。 This is due to the fact that if the program tries to access an attribute or method on a null -reference, a NullPointerException will be thrown. 这是由于以下事实:如果程序尝试访问null引用上的属性或方法,则将引发NullPointerException Just write inputLine == null (in this case, == is correct). 只需inputLine == null (在这种情况下, ==是正确的)即可。 An alternative solution was proposed by Szychan in the comments : You can use Objects.isNull(inputLine) to check whether inputLine is null . Szychan在评论中提出了一个替代解决方案:您可以使用Objects.isNull(inputLine)来检查inputLine是否为null

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

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