到目前为止,这是我的格式:

public class CompSci12A2Recursion {

    /**
     * @param args the command line arguments
     */

    public static void countCharacters(String s){
        String CharCount;
        Integer intCharCount;
        CharCount = JOptionPane.showInputDialog(s);
        if (CharCount.length() == 1){
            System.out.println(CharCount);
        }
    }
    public static void main(String[] args) {
        // TODO code application logic here
        CompSci12A2Recursion mySimpleObject = new CompSci12A2Recursion();
        CompSci12A2Recursion.countCharacters("Type in a word, and it will count how many characters are in it.");

    }

}


我试图做到这一点,以便无论在MessageBox中键入什么内容,它都将使用户知道所说单词中有多少个字符。

最佳答案

递归是吗?尝试这个:

public int count (String str){
     if (str.length == 1)
          return 1;
     else if (str.length == 0)
          return 0;
     else
          return count(str.substring(1)) + 1;
}

07-24 19:59