Home > Back-end >  How to add comms after every number from array using for loop in Java
How to add comms after every number from array using for loop in Java

Time:02-01

I am trying to bring this output: 65, 3, 10 (no comma at the end)

but with my code, I am getting this: 65, 3, , 10

Can anyone help me to write the correct code, please? Here is my code:

static void printArray(int[] validInput, int arrayFill){    //validInput[] = {65, 3, 10};  arrayFill = 3;(size of array)
    for(int i = 0; i < arrayFill; i  )
    {
        for(int j = 0; j < i; j  )
        {
            System.out.print(", ");
        }
        System.out.print(validInput[i]);
    }
}

CodePudding user response:

i dont' know why you used a double for but with this solution (a for with an if condition that stops to print ',' when index is equal to the last cycle) you have the desired output

static void printArray(int[] validInput, int arrayFill){    //validInput[] = {65, 3, 10};  arrayFill = 3;(size of array)
    for(int i = 0; i < arrayFill; i  )
    {
        System.out.print(validInput[i]);
        
        if(i!=arrayFill-1) {
             System.out.print(", ");
        }
    }
}

Result:

65, 3, 10
  •  Tags:  
  • Related