thegoldencanary
thegoldencanary

Reputation: 61

Odd behaviour with StringBuilder, Java

So I've been trying to print out some lines of "-" characters. Why does the following not work?:

StringBuilder horizonRule = new StringBuilder();

for(int i = 0 ; i < 12 ; i++) {
    horizonRule.append("─");
    System.out.println(horizonRule.toString());
}

The correct output is several lines like

─
──
───
────

and so on, but the incorrect output is

â??
â??â??
â??â??â??

I'm guessing the string is not being properly decoded by println or something

Upvotes: 1

Views: 210

Answers (4)

Rico77
Rico77

Reputation: 1

public class myTest1 {

public static void main(String[] args) {
    StringBuilder horizonRule = new StringBuilder();
    for (int i = 0 ; i <= 13 ; i++){
        horizonRule.append('_'); 
        System.out.println(horizonRule.toString());
    }
}

}

is correct; maybe you use a different encoding ? clear env path

Upvotes: 0

Olivier Gr&#233;goire
Olivier Gr&#233;goire

Reputation: 35417

You say that the IDE wants to save as UTF-8. You then probably have saved it as UTF-8.

However your compiler is likely to compile in whatever encoding your system uses.

If you write your code as UTF-8, make sure to compile it with the same encoding:

javac -encoding utf8 MyClass.java

Upvotes: 1

f1sh
f1sh

Reputation: 11934

The string in your code is not a hyphen but a UTF8 box drawing character.

The terminal your application is printing to doesn't seem to expect any UTF8 content, so the issue is not inside your application.

Replace it with a real hyphen (-) or make sure the tool that displays the output supports UTF8.

Upvotes: 3

Stewart
Stewart

Reputation: 18302

I tried your code (I literally just copy'n'paste) using BeanShell, and it worked perfectly. So there's nothing wrong with the code. It will be your environment.

stewart$ bsh
Picked up JAVA_TOOL_OPTIONS: -Djava.awt.headless=true -Dapple.awt.UIElement=true
BeanShell 2.0b4 - by Pat Niemeyer ([email protected])
bsh % StringBuilder horizonRule = new StringBuilder();
bsh % for(int i=0; i<12; i++) {
horizonRule.append("─");
System.out.println(horizonRule.toString());
}
─
──
───
────
─────
──────
───────
────────
─────────
──────────
───────────
────────────
bsh %

Upvotes: 0

Related Questions