简体   繁体   English

设置数组的值不起作用 - 为什么?

[英]Setting a value of an array not working - why?

I am trying to declare an integer array in android studio / java.我正在尝试在 android studio/java 中声明一个整数数组。 When I try to set a value of this array, android studio does not recognize it.当我尝试设置此数组的值时,android studio 无法识别它。

I have tried using String instead of int and other types of arrays but I still get the same result.我曾尝试使用 String 而不是 int 和其他类型的数组,但我仍然得到相同的结果。

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.第二个语句在 Android Studio 中带有下划线,将鼠标悬停在它上面会显示不同类型的错误,这意味着它无法识别该语句。 If I move my pointer over hello I get "unknown class: hello".如果我将指针移到 hello 上,我会得到“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.这实际上是你缺乏的关于 Java 的基本知识,这个问题不应该出现在 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])
    }
}

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

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