使用对象的 if 语句中的表达式非法开始



我现在遇到了一个非常令人沮丧的问题,也许答案就在这里?

我目前遇到 if 语句的问题。 我希望我的核心.java类包含一个 if 语句,如果我的变量计数器达到 2,该语句将关闭整个程序。

private int counter = 0;
//located in the class Ending

我使用单独的方法实现了它addCounter()它作为

public void addCounter(){
this.counter ++;
}
//this will be called in core.java

我还有一个getter它应该返回计数器的值

public int getCounter(){
return counter;
}
//this will be called in core.java

核心变化状态的递减.java

Ending changeState = new Ending();
//(As per request)

真正的问题描述如下:

我似乎想不出一个合适的 if 语句来检查方法 getCounter 在被多次调用后是否达到addCounter();

我的第一个想法是使用诸如

if(changeState.getCounter().equals(2)){
System.exit(0);
}
//I also tried using: 
if(changeState.getCounter() == 2)
//however, that didn't work either

这两行都给了我许多错误,我无法理解:

.java:476: error: illegal start of type: if(changeState.getCounter().equals(2)){

.java:476: error: <identifier> expected: if(changeState.getCounter().equals(2)){

.java:476: error: ';' expected: if(changeState.getCounter().equals(2)){

.java:476: error: illegal start of type: if(changeState.getCounter().equals(2)){

.java:476: error: illegal start of type: if(changeState.getCounter().equals(2)){

.java:476: error: ';' expected: if(changeState.getCounter().equals(2)){

谁能详细说明出了什么问题以及应该做些什么来克服这个问题? 提前谢谢你!

C.C.

.equals(2) 是不正确的,equals 方法中的 2 是基元类型 int 文字,而不是对象或字符串类型

.equals() 方法使用"字符串">类型之一 counter.equals("2")

或者它使用类型"对象"进行比较 .equals(((Object)new String("2")))

如果你必须使用 .equals() 方法,那么它将是

if(counter.getCounter().equals(new Integer(2).toString())){
System.exit(0);
}

虽然这真的应该更简单,例如

if(counter.getCounter() == 2){
System.exit(0);
}

我的回答一直在这里撒谎。

如果其他人遇到类似的问题,似乎您根本无法调用类中的对象,除非它在方法中。

我承认这确实完全解决了我的问题,但它确实向我展示了宝贵的教训。

祝你好运!

最新更新