我嘗試了多個版本,包括在StackOverflow上找到的幾個解決方案,但我總是獲取數字而不是控制檯中的字符。對於我的uni中的作業,我們需要反轉字符串中的字符。但創建新的字符串似乎並不那麼容易。Java字符到字符串
我試圖用一個StringBuilder,
StringBuilder builder = new StringBuilder();
// ...
builder.append(c); // c of type char
字符串連接,
System.out.print("" + c); // c of type char
甚至將String.valueOf(),
System.out.print(String.valueOf(c)); // c of type char
,並用顯式轉換再次他們每個人到char
。但我總是得到序列中字符的序號,而不是控制檯中輸出的實際字符。我如何正確地從char
s建立一個新的字符串?
/**
* Praktikum Informatik - IN0002
* Arbeitsblatt 02 - Aufgabe 2.6 (Buchstaben invertieren)
*/
public class H0206 {
public static String readLine() {
final StringBuilder builder = new StringBuilder();
try {
// Read until a newline character was found.
while (true) {
int c = System.in.read();
if (c == '\n')
break;
builder.append(c);
}
}
catch (java.io.IOException e) {
; // We assume that the end of the stream was reached.
}
return builder.toString();
}
public static void main(String[] args) {
// Read the first line from the terminal.
final String input = readLine();
// Create a lowercase and uppercase version of the line.
final String lowercase = input.toLowerCase();
final String uppercase = input.toUpperCase();
// Convert the string on the fly and print it out.
for (int i=0; i < input.length(); ++i) {
// If the character is the same in the lowercase
// version, we'll use the uppercase version instead.
char c = input.charAt(i);
if (lowercase.charAt(i) == c)
c = uppercase.charAt(i);
System.out.print(Character.toString(c));
}
System.out.println();
}
}
'char'類型的'c'?我在你的例子中看到的是一個'int'。另外,'System.in.read()'做了什麼? – 2014-10-27 15:36:16
['String#valueOf()'shoud work](http://stackoverflow.com/questions/8172420/how-to-convert-a-char-to-a-string-in-java)...你是否確定你的角色不是數字,例如''4''? – sp00m 2014-10-27 15:38:24
'c'可以保存一個字符數據,但肯定是'int'類型而不是'char'。像這樣將它轉換爲char:'char ch =(char)c;'。 – icza 2014-10-27 15:40:18