我正在尝试编写一个程序,它将一个数字转换成它的等效字符串。IE 987,654,321 = 9876654321。我从控制台读取了值,我想遍历从 i = 0 到 string.length 的 while 循环
例子
var s = "987654321"
var characters = s.toString;
var i = 0;
while(i < characters.length){
do something
}
我的代码在下面
object project1 {
def main(args: Array[String]) {
println("Enter a number")
val s = Console.readLine
println(eval(s));
}
def tens(c: Char) : String = (
if (c.toInt == 9){
return "Ninety";
} else if (c.toInt == 8){
return "Eighty";
} else if(c.toInt == 7){
return "Seventy";
} else if(c.toInt == 6){
return "Sixty";
} else if(c.toInt == 5){
return "Fifty";
} else if(c.toInt == 4){
return "Fourty";
} else if(c.toInt == 3){
return "Thirty";
} else if(c.toInt == 2){
return "Twenty";
} else{
return "";
}
)
def everyThingElse(c : Char): String = (
if (c.toInt == 9){
return "Nine";
} else if (c.toInt == 8){
return "Eight";
} else if(c.toInt == 7){
return "Seven";
} else if(c.toInt == 6){
return "Six";
} else if(c.toInt == 5){
return "Five";
} else if(c.toInt == 4){
return "Four";
} else if(c.toInt == 3){
return "Three";
} else if(c.toInt == 2){
return "Two";
} else if(c.toInt == 1){
return "One";
} else{
return "";
}
);
def eval(s: String): String = {
val characters = s.toCharArray;
var word = "";
var i = 0;
while( i < characters.length ){
if((i == 14) || (i == 11) || (i == 8) || (i == 5) || (i == 2)){
word = word + everyThingElse(characters(i));
word = word + " Hundred ";
i += 1;
} else if ((i == 13) || (i == 10) || (i == 7) || (i == 4) || (i == 1)){
if(characters(i).toInt != 1){
word = word + tens(characters(i));
i += 1;
} else{
i += 1;
if(characters(i).toInt == 9){
word = word + " Nineteen ";
} else if(characters(i).toInt == 8){
word = word + " Eighteen ";
} else if(characters(i).toInt ==7){
word = word + " Seventeen ";
} else if(characters(i).toInt == 6){
word = word + " Sixteen ";
} else if(characters(i).toInt == 5){
word = word + " Fifteen ";
} else if(characters(i).toInt == 4){
word = word + " Fourteen ";
} else if(characters(i).toInt == 3){
word = word + " Thirdteen ";
} else if(characters(i).toInt == 2){
word = word + " Twelve ";
} else if(characters(i).toInt == 1){
word = word + " Ten ";
}
i += 1;
}
} else if (i == 9){
word = word + everyThingElse(characters(i));
word = word + " Billion ";
i += 1;
} else if(i == 6){
word = word + everyThingElse(characters(i));
word = word + " Million ";
i += 1;
} else if (i == 12){
word = word + everyThingElse(characters(i));
word = word + " Trillion ";
i += 1;
} else if (i == 0){
word = word + everyThingElse(characters(i));
i += 1;
}
}
}
}