【发布时间】:2016-11-09 13:16:54
【问题描述】:
目标:在 5 次猜测中击败所有计算机 Dot Coms,您将获得评分,即 numOfGuesses
设置:程序启动时,计算机将三个 dotcom 放置在虚拟 7X1 网格上。完成后,游戏会要求您进行第一次猜测。
它是如何工作的:整个过程在命令行上运行,计算机会要求您输入一个猜测(一个单元格),您将在命令行输入“0”,“2”等.作为对你的猜测的回应,你会在命令行中看到一个结果,无论是“Hit”、“Miss”还是“kill”,当你被杀死时,游戏结束时会打印你为杀死所采取的猜测数,即价值变量 numOfGuesses
import java.util.Scanner;
import java.util.ArrayList;
class DotCom
{
private ArrayList<String> locationCells; // to hold the location cells
public void setLocationCells(ArrayList<String> loc) //setter method that takes an int array(which has three cell locations as ints(2,3,4,etc))
{
locationCells = loc;
}
public String checkYourself(String userInput) //method that takes a String for the user's Input("1","3",etc).checks it and returns a result representing a "hit","miss" or "kill".
{
String result = "miss"; //when you miss hit the randomNum value generated
int index = locationCells.indexOf(userInput); //checks the index of the userInput(user's Input),from the locationCells and Stores the value in index int variable
if(index >= 0)
{
locationCells.remove(index); //removes the index position(user's guess)from the array,so that the same value don't get accepted again
if(locationCells.isEmpty()) //if locationCells array goes empty
{
result = "kill"; // when you hit all the three randomNum values
}
else
{
result = "hit"; //when you hit the randomNum value
}
}
System.out.println(result); //print result
return result;
}
}
class DotComTestDrive
{
public static void main(String []args)
{
Scanner user_input = new Scanner(System.in);
int numOfGuesses = 0; //for storing user guesses
DotCom dot = new DotCom(); //dot com instance variable
int randomNum = (int)(Math.random()*5); //to get a random value as an int variable and store in randomNum variable
int[] location = {randomNum,randomNum+1,randomNum+2}; //
dot.setLocationCells(location);
boolean isAlive = true;
while(isAlive == true && numOfGuesses < 6)
{
System.out.println("Enter Your Guess : ");
String userInput = user_input.next(); //take user input(user's guess)
String result = dot.checkYourself(userInput);
numOfGuesses++;
if(result.equals("kill"))
{
isAlive = false;
System.out.println("You Took " + numOfGuesses + " guesses");
}
}
}
}
“int[] 变量无法转换为 ArrayList” 得到以下行“dot.setLocationCells(location);”的上述错误
【问题讨论】:
-
是的,错误信息似乎相当清楚 - 你期望会发生什么?你明白
int[]和ArrayList<String>是完全不同的类型吗? -
疯狂的缩进是怎么回事?
-
@khelwood 我见过你问过几次“疯狂的意图”。虽然我必须承认我觉得它有点有趣,但我不认为这真的算作"being nice",它说“关注帖子,而不是人。这包括即使应用于帖子也感觉个人的术语(比如“懒惰”、“无知”或“发牢骚”)。”。 “疯狂”感觉它属于我的名单。也许只是考虑放弃它?
-
我们对你的游戏不太感兴趣。如果您有与编程相关的问题,请提出,并提供相关代码(而不是完整的“游戏”)。