Resetting array index when reaching last index

Karlo de Leon :

I'm trying to build a code in which the 12 months of the calendar are in an array, the code then asks for a month, and then it outputs the 10 months ahead of the inputted month. (e.g input is January, output would be from February til November.) I'm having trouble reverting the index back to the start once the index exceeds 12, for if example I input August, it's supposed to output September to June, but instead it stops at December and says out of bounds. Thank you

String months[];
   String choice;
    months = new String[13];
   months[0] = null ;
   months[1] = "January";
   months[2] = "February";
   months[3] = "March";
   months[4] = "April";
   months[5] = "May";
   months[6] = "June";
   months[7] = "July";
   months[8] = "August";
   months[9] = "September";
   months[10] = "October";
   months[11] = "November";
   months[12] = "December";
   System.out.print("Enter Month : ");
   choice= a.nextLine();

   if (choice.equals("August"))    {
       for(int i=8; i<i+10; i++) {
           String result= months[i];
           System.out.println(result);
       }
   }
Tim Biegeleisen :

Use the modulus when choosing the month to print:

int start = 8;
if ("August".equals(choice)) {
    for(int i=start; i < start+10; i++) {
        String result= months[i % 12];
        System.out.println(result);
    }
}

This assumes you have defined your months array as:

String[] months = new String[12];
months[0] = "January";
months[1] = "February";
// ...
months[11] = "December";

The idea here is to wrap around the index used to select a month from the array. The dummy variable i, upon hitting the value 12, will wrap around to zero again.

Side note: It is always better to compare a string literal to a variable by placing the literal on the LHS of the comparison. The version I used is immune to a null pointer exception; the version you used is not.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8645&siteId=1