2013-12-23 60 views
1

我是新來的android,我正在嘗試創建一個遊戲。這是一個非常簡單的猜數字遊戲。如果用戶猜測正確,我想更改正確答案的值。我不確定如何做到這一點。他是我創建的代碼:我可以更改最終int值嗎

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?我不得不把它稱爲最終的,並且不能改變它的價值。

+2

「我可以更改最終整數的值」 - 編號 – Maroun

+0

聲明int值 - 全局** ** –

+0

_「我被迫稱之爲最終」_你是如何被迫的? – Baby

回答

7
Can i change value of final int?? 

對於這個答案是否定的。

我能理解你正在使用它的匿名內部類,所以日食強行要求你讓你想中使用correctAnswer值final..So您的問題匿名內部類,以便去除final和定義correctAnswer全球喜歡..

private int correctAnswer; 

則可以更改值,您可以在匿名內部類訪問它

+1

+1來理解問題並解釋原因,以及如何解決它。 –

+0

我試過這樣做,但在onclicklistener裏面它說 不能在一個不同的方法中定義的內部類中引用一個非final變量correctAnswer –

+0

@ArjunKrishnan在onCreate方法外定義它..然後它不會問你.. –

-1

如果我們聲明變量爲final,我們不能更改其值。

刪除final關鍵字,然後您可以更改其值。

+1

他不能刪除最後如果他想在點擊監聽器中使用它 –

1

最後爲var分配在堆棧中,你永遠不能改變它,我的意思是四種八種基本類型var。 final對於引用(或指針),你永遠不能改變引用,但是引用指向的意思是什麼,你可以改變它。例如, final List list = new ArrayList();列表是最終的,它必須是一個ArrayList,但列表中的內容可以更改它。

0

你不能改變final int的值,因爲Java使用關鍵字'final'來聲明常量&如果你試圖修改它,那麼編譯器會產生錯誤!

或者最好不要讓它最終!

0

你需要的是一個容器:

public class IntContaner { 
    public int value; 

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

而在你的代碼,你寫:

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

...它允許你改變 「correctAnswer」 的內容在OnClickListener 。

相關問題