简体   繁体   中英

Setting a value of an array not working - why?

I am trying to declare an integer array in android studio / java. When I try to set a value of this array, android studio does not recognize it.

I have tried using String instead of int and other types of arrays but I still get the same result.

int[] hello = new int[5];
hello[0] = 1;

The second statement is underlined in Android Studio and hovering over it displays different kinds of errors which means it does not recognize the statement. If I move my pointer over hello I get "unknown class: hello". If I move it over other parts of the statement I get "Identifier expected" and "unexpected token".

Edit: I had the semicolon in my original code, I just didn't paste it correctly. As for the whole class:

public class MainActivity extends AppCompatActivity {
    int hello[] = new int[5];
    hello[1] = 2;
    TextView texty;
    String s = String.valueOf(hello[1]);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("mainy", s);
    }

    TextView t1 = findViewById(R.id.textView1);
    TextView t2 = findViewById(R.id.textView2);
    TextView t3 = findViewById(R.id.textView3);
    TextView t4 = findViewById(R.id.textView4);
    TextView t5 = findViewById(R.id.textView5);

    public void nextPage(View view) {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1){
            if (resultCode == RESULT_OK){
                String s = data.getStringExtra(SecondActivity.KEY);
                texty.setText(s);
            }
        }
    }
}

This is actually basic knowledge about Java you lack and this question shouldn't be on stackoverflow. You can't implement logic outside methods. You may only declare variables.

What you should do looks like this:

public class MainActivity extends AppCompatActivity {
    int hello[];
    TextView texty;
    String s;

    void method(){
        hello = new int[5];
        hello[1] = 2;
        s = String.valueOf(hello[1])
    }
}

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.

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