我可以更改final int的值吗?

时间:2013-12-23 07:35:57

标签: java android

我是Android新手,我正在尝试制作游戏。这是一个非常简单的猜数字游戏。如果用户猜对了,我想改变正确答案的值。我不确定该怎么做。他是我创建的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button subm = (Button) findViewById(R.id.button1);
    final TextView tv1 =(TextView) findViewById(R.id.textView1);
    final EditText userG=(EditText)findViewById(R.id.editText1);
    Random rand=new Random();
    final int correctAnswer=rand.nextInt(100)+1;
    subm.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int userNum=Integer.parseInt(userG.getText().toString());
            if(userNum>100 || userNum<0){
                tv1.setText("Enter a number between 1 and 100");
            }
            else{
            if(userNum==correctAnswer){

                tv1.setText("YEAH! You got it right");
            }
            else if(userNum>correctAnswer){

                tv1.setText("Sorry,Your guess is too high");
            }
            else if(userNum<correctAnswer){
                tv1.setText("Sorry,Your guess is too low");
            }}
        }
    });
}

如何更改correctAnswer?我被迫称之为最终,不能改变价值。

5 个答案:

答案 0 :(得分:9)

Can i change value of final int??

对于这个答案是否定的..

我可以理解你在匿名内部类中使用它的问题所以eclipse强行要求你让它成为最终的..所以你想在匿名内部类中使用correctAnswer值,所以删除final并在全球范围内定义正确的答案,如..

private int correctAnswer;

然后您可以更改值,您可以在匿名内部类

中访问它

答案 1 :(得分:1)

最后在堆栈中分配var,你永远不能改变它,我的意思是四种八种基本类型var。 对于引用(或指针)的final,你永远不能更改引用,但是引用的意思是什么,你可以改变它。 例如,final List list = new ArrayList(); list是final,它必须是一个ArrayList,但是在列表中,你可以改变它。

答案 2 :(得分:0)

您无法更改final int的值,因为Java使用关键字“ final ”来声明常量&amp;如果您尝试修改它,那么编译器将生成错误!

或者最好不要让它最终!

答案 3 :(得分:0)

您需要的是一个容器:

public class IntContaner {
    public int value;

    public IntContainer(int initialValue) {
        value = initialValue;
    }
}

在你的代码中,你写道:

final IntContainer correctAnswer=new IntContainer(rand.nextInt(100)+1);

...允许您更改OnClickListener中“correctAnswer”的内容。

答案 4 :(得分:-1)

如果我们将变量声明为final,我们就无法更改其值。

删除final关键字,然后您可以更改其值。

相关问题