java - How to stop incrementing and decrimenting at the end of an array? -


i'm beginner in programming. want make android app 3 views.

  1. text view (display text), ,
  2. buttons (forward , back).

i made array of words one, two, three, four, five displayed. put one on xml.

when user clicks forward shows two when click forward again shows three , when user clicks back shows two. can until poit.

the problem when reaches five , user clicks forward , when reaches one , user clicks back crashes.

i want button nothing, not goes one. want user know end of list. same problem back button. want stays on one. code. please help.

public class aba extends appcompatactivity {      int = 0;     string[] mylist = {         "one",         "two",         "three",         "four",         "five"     };      @override     protected void oncreate(bundle savedinstancestate) {             super.oncreate(savedinstancestate);             setcontentview(r.layout.activity_aba);          }         //incrementing value l on forwardbutton click     public void forwardbutton(view view) {             textview textdisplay = (textview) findviewbyid(r.id.textdisplay);             = + 1;             textdisplay.settext(mylist[i]);             if (i == mylist.length) {                 = + 0;             }         }         //decrementing value l on backbutton click     public void backbutton(view view) {         textview textdisplay = (textview) findviewbyid(r.id.textdisplay);         = - 1;         textdisplay.settext(mylist[i]);         if (i == 0) {             = - 0;         }      } } 

indexing of array starts 0. since array contains 5 elements, value of length 5, indexing goes 0, 1, 2, 3, 4.

this means don't want go below 0 , above 4.

(also, there no reason initialize textview on every button click)

something should work:

int = 0; string[] mylist={"one", "two", "three", "four", "five"}; textview textdisplay;  @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_aba);      textdisplay = (textview) findviewbyid(r.id.textdisplay); }  public void forwardbutton(view view)  {     if(i < mylist.length - 1) {         i++;         textdisplay.settext(mylist[i]);     }  }  public void backbutton(view view)  {     if(i > 0) {         i--;         textdisplay.settext(mylist[i]);     } } 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -