java - Printing a number next to each String -


i have method prints out elements of string array not null. desired output:

1. cook 2. chef 3. baker 4. butcher 5. distiller 

output getting:

1. cook 3. chef 4. baker 7. butcher 9. distiller 

the numbers aren't consecutive in first example. it's because it's printing 'i' when 'i' not null. there anyway can make first example? i've tried different solutions none of them seem work.

public class main {  public void testmethod() {     string myarray[] = new string [] { "cook", null, "chef", "baker", null, null, "butcher", null, "distiller" };     (int = 0; < myarray.length; i++) {         if (myarray[i] != null)              system.out.println((i + 1) + ". " + myarray[i]);     }    }  public static void main(string[] args) {     main main = new main();     main.testmethod(); } } 

just keep counter:

public void testmethod() {     string myarray[] = new string [] { "cook", null, "chef", "baker", null, null, "butcher", null, "distiller" };     int j = 0;     (int = 0; < myarray.length; i++) {         if (myarray[i] != null)  {             system.out.println(++j + ". " + myarray[i]);         }     }    

}


Comments

Popular posts from this blog

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

html - Outlook 2010 Anchor (url/address/link) -

android - How to create dynamically Fragment pager adapter -