0

I'm working on an assignment and the code is working perfectly, except for one small little problem.

For example at the end it's supposed to say, "t,e,s,t" but instead it prints out "t,e,s,t,".

import javax.swing.JOptionPane;
public class program {
    public static int divide(String input)   {
        int length=0; 
        String output = "";
        for (int i=0; i<input.length(); i++) {
            length++;
            output += input.charAt(i);
            output += ",";
        }
        JOptionPane.showMessageDialog(null, "Eingabe: " +input+ "\nAnzahl der Zeichen: " +length+ "\nZeichen: \n" +output);
        return length;
    }
}

I'd just like to say for those who are planning on giving tips, please note that this is an assignment so I'm not really allowed to make any MAJOR changes to it. This program HAS to be:

Solved using a for loop The output HAS to be in JOptionPane It has to be in a method (for I'll have to write an inputDialog later in the main-method, but that's unimportant right now).

My only problem with it, for example the output would have to say (I'll translate the output in english, since I'm at an austrian school) if the string was "hello", the program would say "letters: h, e, l, l, o" but instead it says "h, e, l, l, o," with a comma at the end, how do I get rid of it?

(Also sorry if I messed up any variables, I renamed them all from German to English for this post so I hope I didn't mess any of them up)

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
eiex
  • 17
  • 2

7 Answers7

1

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

Alex Sveshnikov
  • 4,214
  • 1
  • 10
  • 26
1

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.

Always Learning
  • 5,510
  • 2
  • 17
  • 34
1

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.
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
  • Thanks, yeah I've learned about the "Naming Conventions" and forgot to follow them as I was editing the names for this post. – eiex Mar 12 '21 at 11:06
1

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);
    }
WillemH0
  • 29
  • 3
0
  • Your loop iterates through every character, appending both the character and a comma. This includes the final character. You need to find a way to avoid adding a comma after the final iteration;

  • Using String and appending characters one by one is very inefficient. This is what StringBuilder is designed for;

  • What is the purpose of the length variable? It can be replaced with input.length() - 1;

  • String.format() makes your code easier to read rather than chaining together string concatenations;

  • Don't be afraid to use a healthy amount of spacing throughout your code. It is much harder to read otherwise.

Something like this should work well:

public static int divide(String input)   {
    int length = input.length() - 1;
    String output;
    if (input.length() == 0) output = input;
    else {
        StringBuilder outputBuilder = new StringBuilder(input.charAt(0));
        for (int i = 1; i < input.length(); i++) {
            outputBuilder.append(',').append(input.charAt(i));
        }
        output = outputBuilder.toString();
    }

    JOptionPane.showMessageDialog(null, String.format("Eingabe: %s\nAnzahl der Zeichen: %d\nZeichen: \n%s", input, length, output);
    return length;
}
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
bliss
  • 336
  • 2
  • 8
  • This code is above my skill level at the moment, we haven't learned about "toString();" or "StringBuilder outputBuilder = new StringBuilder", Thanks for the advice though, I'll definitely come back to this though once we start learning about those things. – eiex Mar 12 '21 at 11:07
0

I would use a StringJoiner

StringJoiner output = new StringJoiner(",");
for (int i = 0; i < input.length(); i++) {
  length++;
  output.add(input.substring(i, i + 1));
}
JOptionPane.showMessageDialog(… + output.toString());

so You are not allowed to use StringJoiner

String output = "";
String comma = "";
for (int i = 0; i < input.length(); i++) {
  length++;
  output += comma;
  output += input.charAt(i);
  comma = ",";
}
Kaplan
  • 2,572
  • 13
  • 14
  • We haven't learned about this yet. Sorry but I don't really understand what "StringJoiner output = new StringJoiner(",");" means or is supposed to do yet. – eiex Mar 12 '21 at 11:19
  • 1
    Oh, sorry. But this exactly what You need for Your task. It is a class similar to `StringBuilder` or `StringBuffer` that puts strings together while taking care of Your comma-problem. You can additionaly define a `CharSequence` for `StringJoiner` which stands at the beginning and one which stands at the end of Your string. – Kaplan Mar 12 '21 at 11:25
0

Once you learn, use a StringJoiner or similar modern device. My favourite link is at the bottom. There will also be a time when you learn to use a StringBuilder or StringBuffer for assembling a string.

In the meantime, I still like what I learned in my first year of programming: when one iteration through a loop needs to be different, take it out of the loop. In my experience this often gives the clearest code. In your case:

    String input = "Wort";
    String output = "" + input.charAt(0);
    for (int i = 1; i < input.length(); i++) {
        output += ",";
        output += input.charAt(i);
    }
    System.out.println("Zeichen: " + output);

Output:

Zeichen: W,o,r,t

In this case I have taken the first character outside the loop and add it to the output (without comma) already in the declaration of output. The loop starts from index 1 (not 0). Inside the loop I have to add the comma before adding the next char. In other cases one may put the last item outside the loop instead, the result will be the same.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161