2014-03-07 116 views
-1

繼承人的問題:被陷在Java鍛鍊; Tibial

「命理」
創建一個JFrame,它允許一個字的字符串輸入到一個文本框和 程序計算每個字母的總和'輸出值。確保包含「計算」 和「退出」按鈕。 例如:天空= 55,因爲S = 19,K = 11,和y = 25,所以19 + 11 + 25 = 55。

import java.awt.*; //Container, GridLayout, *, or etc... 
    import javax.swing.*; //JFrame, JLabel, *, or etc... 
    import java.awt.event.*; 
    public class NumerologyEC extends JFrame 
    { 
     private static final int Width = 400; 
     private static final int Height = 100; 

     private JLabel wordJL; 
     private JTextField wordTF; 

     private JButton calculateJB, exitJB; 

     private CalculateButtonHandler cbHandler; 
     private ExitButtonHandler ebHandler; 

     public NumerologyEC() 
     { 
      setTitle ("Numerology Extra Credit"); 
      wordJL = new JLabel ("Enter a word: ", SwingConstants.RIGHT); 

      wordTF = new JTextField(10); 

      calculateJB = new JButton ("Calculate"); 
      cbHandler = new CalculateButtonHandler(); 
      calculateJB.addActionListener (cbHandler); 

      exitJB = new JButton ("Exit"); 
      ebHandler = new ExitButtonHandler(); 
      exitJB.addActionListener (ebHandler); 

      Container pane = getContentPane(); 
      pane.setLayout (new GridLayout (2, 2)); 

      pane.add(wordJL); 
      pane.add(wordTF); 
      pane.add(calculateJB); 
      pane.add(exitJB); 

      setSize(Width, Height); 
      setVisible (true); 
      setDefaultCloseOperation (EXIT_ON_CLOSE); 
     } 

      private class CalculateButtonHandler implements ActionListener 
     { 
      public void actionPerformed (ActionEvent e) 
      { 
       String word; 



      } 
     } 

     private class ExitButtonHandler implements ActionListener 
     { 
      public void actionPerformed (ActionEvent e) 
      { 
       System.exit (0); 
      } 
     } 

     public static void main (String[] args) 
     { 
     NumerologyEC rectObject = new NumerologyEC(); 
     } 


    } 

我應該使用什麼方法來解決這個問題?我已經建立了我的jframe,現在我只需要一種方法來解決這個問題。即時通訊只是一個初學者,所以我仍然試圖在編程時弄清楚什麼。任何提示都非常感謝。

回答

0

你需要一個方法sumCharValues接受一個字符串,對字符進行迭代,並添加它們的int值(A = 1,B = 2)並返回總和。例如。

private int sumCharValues (String input) { 
    String str = input.toLowerCase(); // so 'A' and 'a' are equivalent 
    int result = 0; 
    for (int i = 0, n = str.length(); i < n; i++) { 
    char c = str.charAt(i); 
    result += (c - 'a' + 1); 
    } 
    return result; 
} 

你將不得不調用從「計算」處理程序處理這個方法,並有一個JLabel來顯示所得到的值。

+0

謝謝。我不喜歡這裏的其他人讓初學者感到很蠢。這有很大幫助。 – user3390447

+0

很高興提供幫助。不要忘記標記我的答案是正確的:-) –

0

我會建議你閱讀關於事件監聽器。我不會給你直接的答案,但提示。查看Javadocs並查看ActionEvent上可用的方法。谷歌可以是一個方便的工具。