[英]Odd behaviour with StringBuilder, Java
因此,我一直在嘗試打印出一些“-”字符。 為什么以下各項不起作用?:
StringBuilder horizonRule = new StringBuilder();
for(int i = 0 ; i < 12 ; i++) {
horizonRule.append("─");
System.out.println(horizonRule.toString());
}
正確的輸出是幾行,例如
─
──
───
────
依此類推,但輸出不正確
â??
â??â??
â??â??â??
我猜該字符串沒有被println或其他東西正確解碼
您代碼中的字符串不是連字符,而是UTF8框繪圖字符 。
您的應用程序要打印到的終端似乎不需要任何UTF8內容,因此問題不在您的應用程序內部。
將其替換為真實的連字符( -
)或確保顯示輸出的工具支持UTF8。
您說IDE想另存為UTF-8。 然后,您可能已將其另存為UTF-8。
但是,您的編譯器可能會以系統使用的任何編碼進行編譯。
如果您將代碼編寫為UTF-8,請確保使用相同的編碼進行編譯:
javac -encoding utf8 MyClass.java
我使用BeanShell嘗試了您的代碼(實際上只是復制'n'paste),它運行良好。 因此,代碼沒有錯。 這將是您的環境。
stewart$ bsh
Picked up JAVA_TOOL_OPTIONS: -Djava.awt.headless=true -Dapple.awt.UIElement=true
BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh % StringBuilder horizonRule = new StringBuilder();
bsh % for(int i=0; i<12; i++) {
horizonRule.append("─");
System.out.println(horizonRule.toString());
}
─
──
───
────
─────
──────
───────
────────
─────────
──────────
───────────
────────────
bsh %
公共類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());
}
}
}
是正確的; 也許您使用其他編碼? 清除環境路徑
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.