0

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(",");
        }
        } 
        }
        }
        }

2 Answers 2

1

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(",");
     }
 }
Sign up to request clarification or add additional context in comments.

Comments

1

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 = ",";
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.