【问题标题】:Calculate digit sum as a one liner, input has 3 digits将数字总和计算为单行,输入有 3 位
【发布时间】:2020-06-18 15:43:12
【问题描述】:

我必须计算一个字符串中的数字总和(通过扫描仪读取)。另外,我必须确保仅在输入正好是 3 位时才计算输入。

到目前为止我得到了什么:

public class Test{
    public static void main(String... args) {
        System.out.print(new java.util.Scanner(System.in).nextLine().chars().mapToObj(i -> ((char)i)-'0').reduce(0, (a,b)->a+b));
    }
}

但是我怎样才能证明在那一行中正好有 3 位数字呢?

【问题讨论】:

  • 您可以 Arrays.stream 完整输入字符串,然后过滤匹配的正则表达式 \d{3} 然后 findFirst -> 您的代码或其他错误消息?
  • 代码没有3位怎么办?
  • 打印出类似"invalid input"的内容
  • “一个班轮”是指一个声明?因为你可以在 Java 中用一行代码编写任何程序。
  • @Henry,当然是的

标签: java digits


【解决方案1】:

将您的代码包装在 Optional 中,使用 filter() 检查长度并使用 orElse() 提供错误长度输入的输出:

System.out.print(Optional.of(new Scanner(System.in).nextLine())
    .filter(str -> str.matches("\\d{3}")).map(str -> str.chars().sum() - '0' * 3)
    .orElse("invalid input"));

注意可以替换:

.mapToObj(i -> ((char)i)-'0').reduce(0, (a,b)->a+b)

与:

.map(i -> ((char)i)-'0').sum()

或者,因为你正好有 3 位数字,所以:

.sum() - '0' * 3

【讨论】:

  • @Jan 我现在明白你的意思了。我将过滤器更改为filter(str -> str.matches("\\d{3}"))
【解决方案2】:

所以这可能是这样的。添加换行符以提高可读性

public static void main(String... args) {
        System.out.print(
                //Make input into String-Stream
                Arrays.asList(new java.util.Scanner(System.in).nextLine()).stream()
                //Throw away averything not three digits
                     .filter(s -> s.matches("\\d{3}"))
                //Perform digit-sum (make it a String)
                    .map(e -> ""+e.chars().mapToObj(i -> ((char)i)-'0').reduce(0, (a,b)->a+b))
                //return this if there is something
                .findFirst()
                //Or give error message
                .orElse("No valid input!"));
    }

【讨论】:

    【解决方案3】:

    这个怎么样。缺少输出表明输入错误(因为您没有指定在这种情况下要做什么)。

    Stream.of(new Scanner(System.in).nextLine()).
            // three digits
            filter(s->s.matches("\\d{3}"))
            // convert to integer
            .map(Integer::valueOf)
            // find the sum
            .map(n->n/100 + (n/10)%10 + n%10)
            // and print it
            .forEach(System.out::println);
    

    如果您想要一条错误消息,您可以执行以下操作:

    System.out.println(Stream.of(new Scanner(System.in)
                  .nextLine())
                  .filter(a -> a.matches("\\d{3}"))
                  .map(Integer::valueOf)
                  .map(a -> a / 100 + (a / 10) % 10 + a % 10)
                  // convert back to string
                  .map(Object::toString)
                  .findFirst()
                  .orElse("Not 3 digits"));
    
    
    
    

    【讨论】:

      猜你喜欢
      • 2022-07-31
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 2022-09-26
      • 2019-08-24
      • 1970-01-01
      相关资源
      最近更新 更多