简体   繁体   English

接收整数并以字符串形式返回的方法

[英]Method that receives integer and returns in string

I have an exercice to do but i cant seem to do a thing.我有一项运动要做,但我似乎无能为力。 We have to transform an integer that the user chooses and then convert it to string, for ex: input = 2409 output = two, four, zero, nine我们必须转换用户选择的整数,然后将其转换为字符串,例如:输入 = 2409 输出 = 二、四、零、九

if someone could help i would be very appreciated如果有人可以提供帮助,我将不胜感激

i can do only if the input has only one digits, but cant do it with multiple digits.我只能在输入只有一位数字时做,但不能用多位数字做。

First create your hashmap describing the mapping of digits to words.首先创建描述数字到单词映射的hashmap图。 The rest is simple comparison:剩下的就是简单的比较:

public static void printDigitsAsWords(int n) {
  String s = String.valueOf(n); 
  String[] digits = s.split("");
    
  Map<String, String> map = Map.of(
      "0", "zero",
      "1", "one",
      "2", "two",
      "3", "three",
      "4", "four",
      "5", "five",
      "6", "six",
      "7", "seven",
      "8", "eight",
      "9", "nine"
    );
    
  String result = Arrays.stream(digits)
      .map(digit -> map.get(digit))
      .collect(Collectors.joining(", "));

  System.out.println(result);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 接收一个整数并返回传递的数字的阶乘 - Receives one integer and returns the factorial of the number passed 返回整数或字符串的方法 - Method that returns either an integer either a string 如何通过在数字前添加一个字母来简化接收整数列表并返回字符串的 lambda 方法? - How to simplify a lambda method that receives a list of integers and returns a string by adding a letter before the number? Integer.parseInt返回错误:Integer类型的方法parseInt(String)不适用于参数(R.string) - Integer.parseInt Returns an error: The method parseInt(String) in the type Integer is not applicable for the arguments (R.string) 无法分配接收泛型 List 并返回 List 的 Method 返回的结果<?> - Unable to assign the result returned by the Method that receives a generic List and returns a List<?> 如果整数可被3整除,则该方法返回true;如果整数不能被3整除,则该方法返回false。 - The method returns true if the integer is divisible by 3 and returns false if the integer is not divisible by 3 如何通过传递一个整数来实现一个返回字符串的方法,而不需要很多if语句? - How can I implement a method which returns a string by passing an integer, without having lot of if statements? 如何在方法上发布请求返回整数 - How to do post request on a method returns integer 递归方法,返回给定整数的位数 - Recursion method that returns number of digits for a given integer 使用返回整数的辅助方法进行插入排序 - Insertion Sort with a helper method that returns an integer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM