我基本上正在完善,完成并尝试从Java初学者的参考书中编译测试代码 . 目标是创建一个猜谜游戏,其中目标位于3个连续的单元格中(我将这些位置保持在一个数组中),并且用户猜测单元格为no . 通过细胞破坏靶细胞 .
我在同一个错误中检查了六个帖子,但我无法弄清楚出了什么问题 .
这是我的错误:
test.java:5: error: illegal start of expression
public int[] locations={1,2,3};
^
1 error
我的代码是:
public class test{
public static void main(String[] args){
test dot=new test();
public int[] locations={1,2,3};
dot.setLocationCells(locations);
String userGuess="2";
String result = dot.checkYourself(userGuess);
String testResult="failed";
if(result.equals("hit")){
testResult="passed";
}
System.out.println(testResult);
}
public String checkYourself(String stringGuess){
int guess=Integer.parseInt(stringGuess);
String result="miss";
int numOfHits=0;
for(int cell:locations){
if(guess==cell){
result="hit";
numOfHits++;
break;
}
}
if(numOfHits==locations.length){
result="kill";
}
System.out.println(result);
return result;
}
public void setLocationCells( int[] locations){
int[] locns;
locns=locations;
}
}
4 回答
在main方法上面声明上面的变量,代码编译得很好 .
从
int[] locations={1,2,3};
中删除public
关键字 . 方法内不允许访问修饰符,因为其可访问性由其方法范围定义 .如果您的目标是在许多方法中使用此引用,则可能需要将声明移到方法之外 .
方法只能声明局部变量 . 这就是为什么编译器在您尝试将其声明为公共时报告错误的原因 .
如果是局部变量,则不能使用任何类型的访问者(公共,受保护或私有) .
您还应该跟踪静态关键字的含义 . 在方法
checkYourself
中,使用locations
的声明 .静态关键字区分对象创建可访问的元素 . 因为没有对象本身的一部分 .
在main方法之外声明
public static int[] locations={1,2,3};
.