我是java的初学者,我们被要求创建一个程序,读取20到99之间的整数,并将数字写为单词。如果数字大于99或小于20,程序将报告超出范围错误。当用户键入-1时程序停止。
到目前为止,我有这段代码,我不确定是否有任何错误:
import java.util.Scanner;
public class Question1 {
public static void numberToWord(int num, String val) {
String ones[] = {" ", "ONE", "TWO", "THREE", " FOUR", " FIVE", " SIX", " SEVEN", " EIGHT", " NINE", " TEN", " ELEVEN", " TWELVE", " THIRTEEN", " FOURTEEN", " FIFTEEN", " SIXTEEN", " SEVENTEEN", " EIGHTEEN", " NINETEEN"
};
String tens[] = {" ", " ", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"};
if (num > 19) {
System.out.print(tens[num / 10] + " " + ones[num % 10]);
} else {
System.out.print(ones[num]);
}
if (num > 0) {
System.out.println(val);
}
}
public static void main(String[] args) {
int number = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Please type a number between 20 and 99 OR type -1 to end: ");
number = scanner.nextInt();
while(number!=-1){
if(number>=20 && number<=99){
numberToWord((number % 100), " ");
}
else {
System.out.print("Out of bounds. Try Again");
}
System.out.print("\nPlease type a number between 20 and 99 OR type -1 to end: ");
number = scanner.nextInt();
}
}
}
&#13;
答案 0 :(得分:0)
您的代码有效,“FOURTY”一词中只有一个小错字(应该是“FORTY”)。我还会从数组ones
和tens
中的字符串中删除不必要的空格。你在这里插入一个空格:
System.out.print(tens[num / 10] + " " + ones[num % 10]);
所以数组中的空格字符是多余的。
String ones[] = {
"", "ONE", "TWO", "THREE", " FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN",
"ELEVEN", "TWELVE", " THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"
};
String tens[] = {
" ", " ", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"
};
编辑:如果我正在完成这项任务,我可能会编写这样的程序:
import java.util.Scanner;
public class Question1 {
private static String ones[] = {
"", "ONE", "TWO", "THREE", " FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN",
"ELEVEN", "TWELVE", " THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"
};
private static String tens[] = {
" ", " ", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"
};
public static void numberToWord(int num, String val) {
if (num > 19)
System.out.print(tens[num / 10] + " " + ones[num % 10]);
else
System.out.print(ones[num]);
if (num > 0)
System.out.println(val);
}
public static void main(String[] args) {
int number;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("\nPlease type a number between 20 and 99 OR type -1 to end: ");
number = scanner.nextInt();
if (number == -1)
break; // Leave the loop
if (number >= 20 && number <= 99)
numberToWord(number, " ");
else
System.out.print("Out of bounds. Try Again");
}
}
}
但与您的解决方案相比,只有较小的代码样式改进。
祝学习Java好运! :)