-3

我正在尝试为我的 Java 类做作业。我对如何在不使用数组的情况下执行此操作感到非常困惑。要解决的问题是:用户输入一个整数,整数中的每个数字都转换成它的单词形式,但输出的顺序是相反的。例子:

输入:1080

输出:零八零一

输入:-542

输出:减二四五

让我很难理解的事情是试图找出如何在不使用任何类型数组的情况下做到这一点。将单个数字转换为单词只是一个简单的 switch 语句,但是如何读取输入并将每个数字与较大的数字分开呢?您如何将它们重新排列为相反的顺序?

我不是在寻找完整的答案!我只是不明白如何在没有数组的情况下做到这一点。我在互联网上搜索的所有内容都使用数组。

编辑:这是一个 BEGINNER Java 类,伙计们。愤世嫉俗的人看什么都不顺眼...

4

2 回答 2

2

您可以使用模数和除法机制......

if (input < 0) {
   // output 'minus'
   // change it to positiv
   input = -input;
}
while (input > 0) {
    int digit = input % 10;
    // output the digit
    // remove the last digit
    input = input / 10;
}
于 2013-11-02T18:19:36.043 回答
0

I'd create a function that takes a number as an input, uses a for loop with str.length-1 that iterates through each number starting with the last, obtain the integer itself using str.charAt(i) and as you said use a switch statement to turn the number into a String. Then you can compile them using the += operator

Something like this should work

String numberSentence (int input) {
    String total = new String();
    String inputS = input.toString();
    int min = 0;
    if(inputS.charAt(0) == '-'){
      total.concat("Minus ")
      min = 1;
    }
    for(int i = inputS.length-1; i >= min; i--) {
        total.concat(stringify(inputS.charAt(i)));
    }
    return total.toString();
}
String stringify (String letter) {
    String word;
    switch(letter) {
        case "1": word = "one"; // Don't forget the "" !
                  break;
        ... Continued ...
    }
    return word;
}

This same approach can be used when the input is not an int

于 2013-11-02T18:21:06.370 回答