向后打印并在同一行上

时间:2014-02-27 22:18:04

标签: java string printing numbers stringbuilder

此程序的目标是从文件中获取输入并剥离每个数字并将其转换为文本。我们不能使用字符串操作。 例如 1:一 21:两个 150:一五零

但我的看起来像这样:一个21:一个两个150:一个二零五一

嗯,我弄清楚了很多,但是我在一条线上打印地雷然后向后引导我走在正确的道路上

谢谢

public class Main {

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */
public static void main(String[] args) throws FileNotFoundException {
  Scanner scanner = new Scanner(new File("translate.txt"));
  while(scanner.hasNextInt()){
      int number = scanner.nextInt();
       System.out.println(number + ": " +NumberTanslatorTrial.tanslate(number) );
    // System.out.println(number + ": " + NumberTranslator.translate(number));

  }


}

新班级

 public class NumberTanslatorTrial {

final private static String[] txt = {"zero", "one", "two", "three", "four",
    "five", "six", "seven", "eight", "nine"};
static int tempNumber;
static String finalString;
static int tempNumber1;
public static StringBuilder num = new StringBuilder();

public static String tanslate(int number) {
    while (number > 9) {
        tempNumber = number % 10;
        number = number / 10;
        num.append(txt[tempNumber]);
        num.append(" ");
        finalString = num.toString();
    }
    if (number <= 9) {
        num.append(txt[number]);
        num.append(" ");
        finalString = num.toString();
    }
    return finalString;

}

}

2 个答案:

答案 0 :(得分:1)

执行%10然后/ 10的问题是它首先查看最低有效数字。

例如,对于input = 167,您有以下步骤:

  1. 数字= 167%10 = 7
  2. 输入= 167/10 = 16
  3. digit = 16%10 = 6
  4. input = 16/10 = 1
  5. digit = 1%10 = 1
  6. input = 1/10 = 0
  7. 所以你看,你最终得到7分,6分,2分和1分。

    解决此问题的最简单方法是使用堆栈。

    if (number == 0) { 
        return "Zero"; 
    } // special case
    if (number < 0) { // Handle negatives.
       num.append("Negative");
       number = -number;
    }
    List<Integer> stack = new ArrayList<Integer>();
    while (number != 0) {
      stack.add(number % 10);
      number /= 10;
    }
    while (!stack.isEmpty()) {
       int digit = stack.remove(stack.size() - 1); // Pop off the stack.
       if (num.length() != 0) { // Add space if necessary.
          num.append(' ');
       }
       num.append(txt[digit]);
    }
    return num.toString();
    

答案 1 :(得分:0)

您可以尝试以下操作:

  public static String tanslate(int number) {
        StringBuilder num = new StringBuilder(); // if global var should be reinialized with every call to remove old data
        while (number > 0) {  
            int tempNumber = number % 10;  // no need to define the global var
            number = number / 10;
            num.insert(0, " "); //insert at index 0, replace with "\n" for new line
            num.insert(0, txt[tempNumber]);  //insert at index 0
        }
        return num.toString(); // no need to define the global var finalString
   }