How do I get rid of the comma at the end? (Java)

Solution 1:

One of the possibilities is to print comma not after each character, but before every character except the first one.

Solution 2:

You only want to add a comma if there is more data to come after. So you can do it in two ways:

  1. add the comma before the text if there's already something in the string:
        String output = "";
        for (int i=0; i<input.length(); i++) {
            length++;
            if (output.length() > 0) output += ",";
            output += input.charAt(i);
        }
  1. add the comma after unless it's the last element:
        String output = "";
        for (int i=0; i<input.length(); i++) {
            length++;
            output += input.charAt(i);
            if (i < input.length() - 1) output += ",";
        }

Personally I like the first way.

Solution 3:

Hello I used an if statement to check if we are at the first letter and if we are then we don't write a comma, here is the code:

{
        int length = 0;
        String output = "";
        int i = 0;
        
        for ( i = 0; i < input.length(); i++)
        {
            if(i == 0)
            {
                length++;
                output += input.charAt(i);


            }
            else
            {
                output += ",";
                output += input.charAt(i);
                length++;
            }
            
           
        }
        Console.WriteLine(output);
    }

Solution 4:

You only need to check whether you are at the last character, and if you are, then break out from the loop.

for (int i=0; i<input.length(); i++) {
    length++; //you do not seem to need this
    output += input.charAt(i);
    if (i==(input.length()-1)) break; //checking whether we are at the last character
    output += ",";
}

Two additional notes:

  1. Please follow the Java Naming Conventions and use PascalCase for your class names, this is very important;
  2. It would make your code much more efficient if you'd use StringBuilder instead of String, to concatenate characters and dynamically build your string. String is immutable and per each concatenation, you're actually creating a new instance of it, which is expensive.