我的 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;
}
}