12dec1990
12dec1990

Reputation: 115

Inserting commas between each odd array output in java

This program uses arrays to print out every odd user input.I have a counter to keep track of the total number of odd items.Everything works fine till the end where there's supposed to be commas between each output and a period at the end of the list.What conditional statement should I insert to make the code print out the number of commas one LESS than the total outputs?

import java.util.*;

public class ManipulatingArrays {
    public static void main(String[]args)
    {
        int counter=0;
        int i;
        String[] list=new String[50];

        for( i=0;i<50;i++)

        {

            Scanner a=new Scanner(System.in);
            System.out.println("Enter something: ");
            list[i]=a.nextLine();
            if(i>=1)
            {

            if(list[i].equals(list[i-1]))
            {
                System.out.println("Program has ended!");
                i=50;


                for( i=0;i<list.length;i+=2)
                {
                    if(list[i]==null)
                    {
                        i=50;
                    }
                    else
                    {
                    counter=counter+1;

            }
            }
            }
            }
            }
        System.out.println("\nTotal number of odd objects: "+counter);
        System.out.print("Every item you like: ");
        for( i=0;i<list.length;i+=2)
        {
            if(list[i]==null)
            {
                i=50;
            }
            else
            {
            System.out.print(list[i]);


        for(int comma=0;comma<1;comma++)
        {

            System.out.print(",");
        }
        } 
        }
        }
        }

Upvotes: 0

Views: 334

Answers (2)

gknicker
gknicker

Reputation: 5569

My favorite way to do this is to initialize a separator variable to an empty string, then set it to some useful value after the first iteration:

    String separator = "";
    for (i = 0; i < list.length; i += 2) {
        if (list[i] == null) {
            break;
        }
        System.out.print(separator);
        System.out.print(list[i]);
        separator = ",";
    }

Upvotes: 1

Akash Thakare
Akash Thakare

Reputation: 22972

You can iterate and check whether it's a last element of array or not.

 for(int comma=0;comma<list.length;comma++){
     System.out.print(list[comma]);
     if(comma != list.length-1) {//This will not add , in last element
       System.out.print(",");
     }
 }

Upvotes: 1

Related Questions