java - How do I remove/not display the null values from two arrays? -


my code works fine. output seems incorrect when enter -1 name or age input. how remove null values , "-1" , display existed array?

import java.util.scanner;  public class quizloop {     private static scanner key = new scanner(system.in);     private static scanner keynum = new scanner(system.in);      public final static int arrayloop = 5;     public static string[] namelist = new string[arrayloop];     public static int[] age = new int[arrayloop];      public static void main(string[] args) {         system.out.println("name & age system\n-----------------\n");         for(int i=0; i<arrayloop; i++) {             system.out.print("name: ");             namelist[i] = key.nextline();             if(namelist[i].equals("-1"))                 break;              system.out.print("age: ");             age[i] = keynum.nextint();             if(age[i] < 0)                 break;         }          system.out.println("----------");         for(int i=0; i<namelist.length; i++) {             system.out.println(namelist[i] + " " + age[i]);         }     } } 

currently, when input -1, loop exits. is, input -1, loop not run again. because use break statement.

if you'd let -1 allow user start current entry again, you'll need 2 things:

if (namelist[i].equals("-1")) {     // take loop variable down one.     i--;     // instead of break, continue next iteration.     continue; } 

if want keep loop how is, print non-null values, modify printing code:

for(int i=0; i<namelist.length; i++) {     if (namelist[i] == null || namelist[i].equals("-1") || age[i] < 0) {         // invalid; go next one.         continue;     } else { // (not strictly necessary)         system.out.println(namelist[i] + " " + age[i]);     } } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -