我正在尝试仅将数字转换为0到100之间的单词,如果不满足条件而不退出该程序,如何重新执行该程序。 如果我输入55,我想输出55,但是如果我键入的数字不在0-100之间,它将输出“您应该输入0-100仅重试一次”,然后它将自动转到“输入数字0之间仅限-100”
package convertnumbertowords;
import java.util.Scanner;
public class ConvertNumberToWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input number between 0-100 only ");
int num1 = sc.nextInt();
while (num1 <= -1 && num1 >= 101 ){
if(num1 <= 100 && num1 >= 0){
System.out.println("The "+num1+" in words is "+
Integer.toString(num1));
}
else{
System.out.println("You should input 0-100 only Try Again");
}
}
}
}
答案 0 :(得分:1)
我的建议是将单词保留在一个数组中,将其分隔为一个,然后拉伸。 例如:
String ones[] = { " ", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine", " Ten"," Eleven", " Twelve", " Thirteen", " Fourteen", "Fifteen", "Sixteen", " Seventeen", " Eighteen"," Nineteen" };
我将ones [0]保留为空的原因,这样很容易理解,ones [1] =一个
String tens[] = { " ", " ", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", "Seventy", " Eighty", " Ninety" };
我将0和10保留为空,因为我已经在其中声明了它。
根据我的示例,如果小于该值,则仅使用ones [number]。如果大于19,我建议将其除以10得到十个单词的单词,然后将数字模量(%)除以10得到一个单词。尽力而为,我的建议可能不是完美的,但希望它能给您一些想法
答案 1 :(得分:0)
要保持输入正确的输入,您首先要输入->检查是否错误->如果是,则再次提示用户,否则继续下一步。在代码中看起来像这样
// Ask for input
System.out.println("Input number between 0-100 only ");
int num = sc.nextInt();
// Check if input is incorrect
while (num > 100 || num < 0) {
// If input is incorrect prompt user again
System.out.println("You should input 0-100 only Try Again");
// Update num and check until unser enters a num within the range
num = sc.nextInt();
}