2015-08-15 114 views
0

我正在編寫一段代碼,提取單詞的第一個首字母並將其作爲首字母縮寫詞。Java:JOptionPane存在的問題/將輸出存儲到變量中

例如句子是random number gen答案是RNG

我有它的工作,但我想在JOptionPane顯示結果。我無法確定如何將最終輸出(3個首字母)保存到變量中,然後在JOptionPane中顯示它。

有沒有一種方法可以將System.out.print輸出存儲到字符串變量中?

我最初試圖將System.out.print存儲到一個變量,但它給了我一個void的錯誤無法轉換爲字符串。

所以我試圖將字母存儲到變量'首字母縮寫',但它只存儲一個(這是有道理的)。 import javax.swing.JOptionPane;

public class ThreeLetterAcronym { 

    public static void main(String[] args) { 
     String answer; 
     String upperAnswer; 
     int number; 
     char letter; 
     String initial = ""; 

     answer = JOptionPane.showInputDialog(null, "Please enter three words?", "Input", JOptionPane.QUESTION_MESSAGE); 
     upperAnswer = answer.toUpperCase(); 
     upperAnswer = " " + upperAnswer; 
     number = upperAnswer.length(); 

     StringBuilder sb = new StringBuilder(); 

     for (int i = 0; i < number; i++) { 
      letter = upperAnswer.charAt(i); 
      if (letter == ' ') { 
       initial = Character.toString(upperAnswer.charAt(i + 1)); 
       sb.append(initial); 
       System.out.print(upperAnswer.charAt(i + 1)); 
      } 
     } 
     JOptionPane.showMessageDialog(null, sb.toString(), "Acronym", JOptionPane.INFORMATION_MESSAGE); 
    } 
} 

回答

1

你在你的輸出消息對話框,將在繼續循環和存儲最後一個每次重置使用initial。所以,我將它存儲到StringBuilder。這裏是工作代碼,

import javax.swing.JOptionPane; 

public class ThreeLetterAcronym { 

    public static void main(String[] args) { 
     String answer; 
     String upperAnswer; 
     int number; 
     char letter; 
     String initial = ""; 

     answer = JOptionPane.showInputDialog(null, "Please enter three words?", "Input", JOptionPane.QUESTION_MESSAGE); 
     upperAnswer = answer.toUpperCase(); 
     upperAnswer = " " + upperAnswer; 
     number = upperAnswer.length(); 

     StringBuilder sb = new StringBuilder(); 

     for (int i = 0; i < number; i++) { 
      letter = upperAnswer.charAt(i); 
      if (letter == ' ') { 
       initial = Character.toString(upperAnswer.charAt(i + 1)); 
       sb.append(initial); 
       System.out.print(upperAnswer.charAt(i + 1)); 
      } 
     } 
     JOptionPane.showMessageDialog(null, sb.toString(), "Acronym", JOptionPane.INFORMATION_MESSAGE); 
    } 
} 
+0

我沒有考慮使用StringBuilder。謝謝。 – BeginnerHelp

+0

這解決了我的問題。 – BeginnerHelp