String无法转换为ArrayList <string>错误

时间:2016-03-14 14:51:16

标签: java arraylist

这是一个类似于沉没的战舰游戏的程序,从头脑第一个java。编译后我收到错误:&#34;字符串无法转换为ArrayList错误&#34;和^指针指向我有两个不同的文件,一个用main方法,另一个用另一个类。这里有什么不对。

主要方法类

import java.util.Scanner;
public class SimpleDotComTestDrive{

   public static void main(String[] args){

      SimpleDotCom dot=new SimpleDotCom();
      boolean repeat=false;
      String[] locations={"2","3","4"};
      dot.setLocationCells(locations);   //^ where compiler points the error
      Scanner input=new Scanner(System.in);
      System.out.println("Lets Start");

      while(repeat==false) {
         System.out.println("Type your guess");
         String userGuess=input.nextLine();
         String result=dot.checkYourSelf(userGuess);
         System.out.println(result);

         if(result=="kill") {
            repeat=true;
            break;
         }
      }
   } //close main
} //close test class

单独保存的课程,这是该课程的一部分:

import java.util.ArrayList;

public class SimpleDotCom {
   private ArrayList<String>locationCells;

   public void setLocationCells(ArrayList<String> locs) {
      locationCells=locs;
   }

   public String checkYourSelf(String userGuess) {
      String result="miss";
      int index = locationCells.indexOf(userGuess);
      if(index>=0) { 
         locationCells.remove(index);

         if(locationCells.isEmpty()) {
            result="kill";
         }
         else {
            result="hit";
         }
    }
    return result;
  } //close check yourself method
} //close simple class

2 个答案:

答案 0 :(得分:2)

您收到错误是因为setLocationCells()方法接受ArrayList<String>并且您通过执行以下操作传递字符串数组:

dot.setLocationCells(locations);

您应该替换方法以接受String[]而不是ArrayList<String>,或者更改您的代码,如下所示:

dot.setLocationCells(new ArrayList<String>(Arrays.asList(locations));

答案 1 :(得分:0)

您不能拥有String[] locations={"2","3","4"};,然后将其解析为需要setLocationCells(ArrayList<String> locs){的方法ArrayList

所以,还有更多方法:

  1. 使用以下代码将数组转换为列表:new ArrayList<String>(Arrays.asList(locations);
  2. 改为定义ArrayList:

    ArrayList<String> list = new ArrayList<String>() {{
        add("2");
        add("3");
        add("4");
    }};
    
  3. 根本改变你的方法:

    public void setLocationCells(String[] locs){
        Collections.addAll(locationcells, locs);
    }