Reputation: 1
Here is a program similar to the sinking battleship game from the book head first java. After compiling I am getting the error: "String cannot be converted to ArrayList Error" and ^ pointer point to the line I have two different files one with the main method and other a separate class. Whats wrong here.
Main method class
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
Separately saved class which is part of this program:
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
Upvotes: 0
Views: 10549
Reputation: 44378
You cannot have String[] locations={"2","3","4"};
and then parse it to the method setLocationCells(ArrayList<String> locs){
that requires the ArrayList
.
So, there are more ways:
new ArrayList<String>(Arrays.asList(locations);
Define the ArrayList instead:
ArrayList<String> list = new ArrayList<String>() {{
add("2");
add("3");
add("4");
}};
Change your method at all:
public void setLocationCells(String[] locs){
Collections.addAll(locationcells, locs);
}
Upvotes: 0
Reputation: 9648
You are getting the error because setLocationCells()
method accepts an ArrayList<String>
and you are passing it a String Array by doing:
dot.setLocationCells(locations);
You should either replace your method to accept String[]
instead of ArrayList<String>
or change your code as follows:
dot.setLocationCells(new ArrayList<String>(Arrays.asList(locations));
Upvotes: 2