2017-05-25 48 views
-2

這是一個用於堆棧的代碼; 點擊按鈕號碼被添加到棧中,推送被顯示在文本視圖上,類似地,點擊推式號碼被從棧中推入。但只有一次操作完成或交替,我不能推兩次。此應用程序的此代碼只運行一次,應用程序停止工作

Button b1 = (Button) findViewById(R.id.btn1); 
    b1.setOnClickListener(this); 
    Button b2 = (Button) findViewById(R.id.btn2); 
    b2.setOnClickListener(this); 
    EditText e1 = (EditText) findViewById(R.id.etn1); 
    x = e1.getId(); 
} 
@Override 
public void onClick(View v) { 
    TextView t1 = (TextView) findViewById(R.id.tvn); 

    if (v.getId()== R.id.btn1) { 
    Stack s1 = new Stack(); 
     s1.push(x); 
     EditText e1 = (EditText) findViewById(R.id.etn1); 
     e1.setId(0); 

     t1.setText("Pushed"); 
     t1.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left)); 
    } 
    else if (v.getId() == R.id.btn2) { 
     Stack s2 = new Stack(); 
     s2.pop(); 
     t1.setText("Poped"); 
     t1.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left)); 
} 
} 
} 
+1

你會幫助我們,如果你給我們的堆棧跟蹤 –

+0

初始化內部onCreateMethod –

回答

0

則很可能是在s2.pop()越來越NullPointerException。您正嘗試popnull對象,因爲您的堆棧中沒有objects2

1.嘗試使用單個Stack並宣佈它作爲global並將其用於既pushpop操作。

2.任何pop操作檢查的天氣之前,stackempty與否。

試試這個:

public class YourActivity extends AppCompatActivity { 

    ........ 
    ................ 

    Stack stack; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     ........ 
     ................ 

     Button b1 = (Button) findViewById(R.id.btn1); 
     b1.setOnClickListener(this); 
     Button b2 = (Button) findViewById(R.id.btn2); 
     b2.setOnClickListener(this); 
     EditText e1 = (EditText) findViewById(R.id.etn1); 

     // Stack 
     stack = new Stack(); 
    } 

    @Override 
    public void onClick(View v) { 
     TextView t1 = (TextView) findViewById(R.id.tvn); 

     // Get id 
     x = e1.getId(); 

     if (v.getId()== R.id.btn1) { 

      // Push 
      stack.push(x); 

      EditText e1 = (EditText) findViewById(R.id.etn1); 
      e1.setId(0); 

      t1.setText("Pushed"); 
      t1.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left)); 
     } 
     else if (v.getId() == R.id.btn2) { 

      if (stack.empty()) { 
       // Show message 
       Toast.makeText(getApplicationContext(), "Stack is empty!", Toast.LENGTH_SHORT).show(); 
      } else { 
       // Pop 
       stack.pop(); 

       t1.setText("Poped"); 
       t1.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left)); 
      } 
     } 
    } 
} 

希望這將有助於〜

+1

的觀點是這個工程的感謝 –

+0

高興知道。如果我的答案有幫助,請點擊勾號將此答案標記爲正確答案。在此先感謝:)閱讀:https://stackoverflow.com/help/someone-answers – FAT

相關問題