java中非法的表达式开始什么意思_Java错误:表达式的非法开头

小编典典

方法只能声明局部变量。这就是为什么当您尝试将其声明为public时,编译器会报告错误的原因。

对于局部变量,您不能使用任何类型的访问器(公共,受保护或私有)。

您还应该知道static关键字的含义。在方法中checkYourself,您使用Integer数组locations。

static关键字区分对象创建可访问的元素。因此,它们不是对象本身的一部分。

public class Test { //Capitalized name for classes are used in Java

private final init[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later.

public Test(int[] locations) {

this.locations = locations;//To access to class member, when method argument has the same name use `this` key word.

}

public boolean checkYourSelf(int value) { //This method is accessed only from a object.

for(int location : locations) {

if(location == value) {

return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method.

}

}

return false; //Method should be simple and perform one task. So you can get more flexibility.

}

public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it.

public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place.

Test test = new Test(Test.locations); //We declare variable test, and create new instance (object) of class Test.

String result;

if(test.checkYourSelf(2)) {//We moved outside the string

result = "Hurray";

} else {

result = "Try again"

}

System.out.println(result); //We have only one place where write is done. Easy to change in future.

}

}

2020-09-16

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值