gpt4 book ai didi

java - 将数字转换为单词并在输入无效时重新执行

转载 作者:行者123 更新时间:2023-12-02 09:36:44 26 4
gpt4 key购买 nike

我试图将数字从 0-100 转换为单词,如果不满足条件而不退出程序,我该如何重新执行该程序。如果我输入55,我想输出55,但如果我输入不在0-100范围内的数字,它会输出“you should input 0-100 only try again”然后它会自动转到“输入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");
}
}
}
}

最佳答案

我的建议是将单词保留在一个数组中,将其分隔为个位和十位。例如:

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] = one

String tens[] = { " ", " ", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", "Seventy", " Eighty", " Ninety" };

我将 0、10 保留为空,因为我已在 1 中声明了它。

根据我的示例,如果小于该值,则使用 Ones[number]。如果它超过 19 ,我建议将其除以 10 以获得其十位单词,然后将数字与 10 取模(%)以获得其个位单词。祝你破解它一切顺利,我的建议可能并不完美,但希望它能给你一些想法

关于java - 将数字转换为单词并在输入无效时重新执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57448032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com