I've got a class defined in a .java file outside of the main activity as follows.
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. What am I doing wrong? I was able to get this class to behave as an object in 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. (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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.