你要做的是,使用JOptionPane作爲源來獲取來自用戶的輸入,所以你不需要掃描器。一旦你從用戶存儲字符串,那麼你可以用它來實例化一個StringBuilder。
使用JOptionPane.showMessageDialog時,必須傳遞null作爲組件的第一個參數。
String string = JOptionPane.showInputDialog("Please input a string");
StringBuilder sb = new StringBuilder(string);
JOptionPane.showMessageDialog(null, sb.reverse().toString());
更完整和驗證需求的解決方案看起來如下:
public static void main(String... args) {
String string = JOptionPane.showInputDialog("Input a String to reverse it");
if (string != null && string.length() > 0) {
StringBuilder reversedString = new StringBuilder(string);
JOptionPane.showMessageDialog(null, reversedString.reverse().toString());
} else {
//validation in case Cancel/Close button or empty input provided
if (string == null) {
JOptionPane.showMessageDialog(null, "No input provided.");
} else {
JOptionPane.showMessageDialog(null, "empty input provided.");
}
}
}
要反轉String
不使用StringBuilder
你可以使用一個for loop
的這樣做。你開始在原始字符串上一次循環一個字符,但是,你從頭開始並開始。在循環內部,一次創建一個字符,創建原始字符串的反轉。見下文:
String originalString= JOptionPane.showInputDialog("Please input a string");
String reversed = "";
//loop from end of string to the beginning
for(int i = originalString.length()-1; i >= 0; i--) {
/*
* Use the previous value of reversed, add to it new character
* this addition causes a new string to be created internally since
* String is immutable
*/
reversed += originalString.charAt(i);
}
JOptionPane.showMessageDialog(null, reversed);
來源
2015-12-03 01:25:51
Raf
請張貼相關碼,優選地是[最小,完整的,並且實施例可驗證程序](http://stackoverflow.com/help/麥克),這裏有你的問題,而不是鏈接。鏈接可能會死亡,鏈接可能包含大型節目,節目太大而無法請求志願者進行審查。您對此要求的遵守情況將不勝感激,並可能幫助您獲得更好更快的幫助。 –
那裏。這次我爲你做了。 –