0

我的 cs 课的这项作业的目标是在字符串中搜索数字并将它们更改为书面形式

前任:4 -> four

这是一个相对简单的任务。但是我有两个问题:

1)由于我当前的代码,如果我转换一个只有"8"的字符串并尝试使其成为"8",它将不起作用,因为它比字符串的当前长度长。

2)通过字符串连续处理多个数字char。我有点想通了。如果你运行我所拥有的东西,它肯定Strings会起作用。我们应该用连字符分隔多个数字字符。

这是我的代码:

public class NumberConversion {

    /**
     * * Class Constants **
     */
    /**
     * * Class Variables **
     */

    /* No class variables are needed due to the applet not having a state.
     All it does is simply convert. */
    /**
     * * Class Arrays **
     */
    char numberChar[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    String numbers[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

    /**
     * * Accessor Methods **
     */
    /**
     * * Transformer/Mutator Methods **
     */
    public void writeNumber(String phrase) {
        /**
         * Local Variables *
         */
        String newPhrase = "";
        int j = 0;
        int k = 0;

        phrase = phrase.trim();

        /**
         * * Counts through the length of phrase **
         */
        for (int i = 0; i < phrase.length(); i++) {
            /**
             * * If the current char is a number char, enter the next repitition
             * structure **
             */
            int l = i + 1;

            if (isNumber(phrase.charAt(i)) && isNumber(phrase.charAt(i + 1))) {
                boolean searchArray = true;

                do {
                    if (numberChar[ j] == phrase.charAt(i)) {
                        searchArray = false;
                    }

                    j++;

                } while (searchArray && j < numberChar.length);

                phrase = phrase.replace(Character.toString(phrase.charAt(i)), numbers[ j - 1] + "-"); //error HERE

            }

            if (isNumber(phrase.charAt(i))) {
                boolean searchArray = true;

                do {
                    /**
                     * * Counts through numberChar array to see which char was
                     * found in the phrase. Stops when found **
                     */
                    if (numberChar[ k] == phrase.charAt(i)) {
                        searchArray = false;
                    }

                    k++;

                } while (searchArray && k <= numberChar.length);

                /**
                 * * Changes char to string and replaces it with the matching
                 * String numbers array element **
                 */
                phrase = phrase.replace(Character.toString(phrase.charAt(i)), numbers[ k - 1]);
            }
            phrase = phrase.replace("- ", " ");
        }
        System.out.println(phrase); // Prints the changed phrase.
    }

    /**
     * * Helper Methods **
     */
    /**
     * * Observer Methods **
     */
    public boolean isNumber(char input) {
        boolean isNumber = false; // Initially fails

        for (int i = 0; i < numberChar.length; i++) {
            /**
             * * If input matches a number char, method returns true **
             */
            if (input == numberChar[ i]) {
                isNumber = true;
            }
        }
        return isNumber;
    }
}
4

3 回答 3

0
    public class NumberConversion

{

/*** Class Variables ***/

/* No class variables are needed due to the applet not having a state.
   All it does is simply convert. */

/*** Class Arrays ***/

char numberChar[] = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' };

字符串 numberWord[] = { “零”、“一”、“二”、“三”、“四”、“五”、“六”、“七”、“八”、“九”};

/*** Transformer/Mutator Methods ***/

public String writeNumber( String phrase ) { /** 局部变量 **/

  phrase = phrase.trim();

  /*** Counts through the length of phrase ***/

    for ( int i = 0; i < phrase.length(); i++ )
    {

     /*** If current char is a number, count through the array
          that contains the number chars until the one needed is
          found. ***/

        if ( isNumber( phrase.charAt( i ) ) )
        {
            boolean keepSearching = true;

            int j = 0;

            do
            {
               if ( numberChar[ j ] == phrase.charAt( i ) )
                  keepSearching = false;

               else
                  j++; // Increments j if char doesn't match array element

            } while ( keepSearching && j < numberChar.length );

            /*** Replaces the current char with the corresponding String
                 word from the other number array.  ***/

            phrase = phrase.replace( Character.toString(
                                      phrase.charAt( i ) ) ,
                                      numberWord[ j ] + "-" );
    }
    }

    /*** Gets rid of dashes from unwanted places ***/

    phrase = phrase.replaceAll( "- " , " " );
    phrase = phrase.replaceAll( "-," , ", " );
    phrase = phrase.replace( "-." , "." );

    if ( phrase.charAt( phrase.length() - 1 ) == '-' )
       phrase = phrase.substring( 0 , phrase.length() - 1 );

  return phrase;
}

/*** Observer Methods ***/

public boolean isNumber( char input ) { boolean isNumber = false; // 最初失败

    for ( int i = 0; i < numberChar.length; i++ )
    {
        /*** If input matches a number char, method returns true ***/

        if ( input == numberChar[ i ] )
           isNumber = true;
    }

    return isNumber;
}
于 2013-04-28T23:52:09.847 回答
0

我会使用 String.replace

for(int i = 0; i < 10; i++) {
   str = str.replace(numberChar[i] + "", numbers[i]);
}
于 2013-04-26T03:00:46.217 回答
0

不要替换当前字符串中的数字,创建一个新字符串并继续追加。然后,您可以避免许多不必要的验证。

    List<Char> myNumberChar = Arrays.asList(numberChar);
    List<Char> myNumbers = Arrays.asList(numbers);
    StringBuilder mySB = new StringBuilder();
    //String myResultString = ""; // If you don't want to use StringBuilder
    for (int i = 0; i < phrase.length(); i++) {
        mySB.append(myNumbers.get(myNumberChar.getIndexOf(phrase.charAt(i)))+"-");
        //myResultString = myResultString + myNumbers.get(myNumberChar.getIndexOf(phrase.charAt(i)))+"-"; //Again, for no StringBuilder case
    }
    String myResult = mySB.toString();
    // No need to do the above in no StringBuilder case, just use myResultString in place of myResult
    System.out.println(myResult.subString(0, myResult.length - 1)); // removed the last hyphen
于 2013-04-26T02:40:59.330 回答