简体   繁体   English

IntelliJ-创建对象时可以识别类,但是方法不会自动完成或编译

[英]IntelliJ - Class is recognized when creating object, but methods are won't autocomplete or compile

I've got a class defined in a .java file outside of the main activity as follows. 我在主要活动之外的.java文件中定义了一个类,如下所示。

package com.example.someGuy.numbershapes;

class Number {

        public int input;

        public boolean isSquare(){
            int sqrtOfInput = (int) Math.sqrt(input);
            if (input == sqrtOfInput * sqrtOfInput) return true;
            else return false;
        }
        public boolean isTriangle(){
            int sqrtOfInput = (int) Math.sqrt(input * 2);
            if (input == sqrtOfInput * (sqrtOfInput + 1)/2) return true;
            else return false;
        }
}

I then try to access it from the main activity like this. 然后,我尝试从这样的主要活动中访问它。

package com.example.someGuy.numbershapes;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    Number myNumber = new Number();

    myNumber.input = 22;

    if (myNumber.isTriangular()){
        //do something
    }
    else if (myNumber.isSquare()){
        //do something else        
    }
}

When I try to run/build the project in IntelliJ, I get an error saying that there is an identifier expected, and illegal start of type error. 当我尝试在IntelliJ中运行/构建项目时,出现一条错误消息,提示存在预期的标识符,并且非法启动类型错误。 What am I doing wrong? 我究竟做错了什么? I was able to get this class to behave as an object in browxy. 我能够使此类在browxy中充当对象。 What am I doing wrong in this case? 我在这种情况下做错了什么? I'm trying to set the input to a text field in the layout and get it to run through the functions I have defined so that I can determine if the number input by the user is triangular, a perfect square, both or neither. 我正在尝试将输入设置为布局中的文本字段,并使其通过我定义的功能运行,以便我可以确定用户输入的数字是三角形,理想正方形还是两者都不是。

You need to put this code 您需要输入此代码

myNumber.input = 22;

if (myNumber.isTriangular()){
    //do something
}
else if (myNumber.isSquare()){
    //do something else        
}

inside the onCreate method, as statements have to appear in a block of code. onCreate方法中,因为语句必须出现在代码块中。 (The block would be a method for the example) (该块将是示例的方法)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Number myNumber = new Number();
    myNumber.input = 22;

    if (myNumber.isTriangular()){
        //do something
    }
    else if (myNumber.isSquare()){
        //do something else        
    }
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM