数値を同等の文字列に変換するプログラムを作成しようとしています。IE 987,654,321 =987百万6,54,3,21。コンソールから値を読み込み、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;
}
}
}
}