What’s wrong with this code?

There’s a code snippet. What’s wrong with it?

StringBuffer sb = new StringBuffer(" - The required object is unknown: ");
sb.append("Please choose an object from [");
for (String tmp : objs) {
    sb.append(' ');

5 Responses to “What’s wrong with this code?”

  1. Levan Says:

    If “objs” is an array or some list of objects, then In the foreach loop you’ll get an exception (which is not a surprise in this case):

    error: incompatible types
    		for (String tmp : objs) {
    required: String
    found: Object

    where instead of Object can be any other, well, object type.

    If the “objs” is an array / list of strings (in which case the name is very misleading), this it will compile without a problem.

    Как то так ))

    • Alexey Ivanov Says:

      Thank you for your comment. 🙂
      I didn’t say the code could be compiled successfully, yet I assumed it could. The misleading name of objs is used because the variable holds a list of objects for user to select from. I’m pretty sure objs has type List<String> (or another Collection-type) or String[].

      A hint: the issue would be seen in runtime if the resulting string is captured to a text file instead of being printed to a terminal.

      • Levan Says:

        Ah, you probably mean the backspace character ‘\b’. When the resulting string is written to a file, the backspace character ‘\b’ will be written as is (depending on which editor you’ll open the file with, the backspace character can be represented differently), i.e. it won’t work as a control character the same way as in the terminal where it will move the printing position back one character space back (in the code example it will result in erasing the last space and printing the closing ‘]’ instead).

  2. Backspace character | Programming is my life Says:

    […] December I asked a question: What’s wrong with this code? I agree that the question was rather broad without context. I just asked it in the same way a […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: