【问题标题】:Can a return statement be formatted like a printf?可以像 printf 一样格式化返回语句吗?
【发布时间】:2014-06-21 02:21:02
【问题描述】:

我是java新手,所以如果这是一个“愚蠢”的问题,请耐心等待。有没有办法格式化类似于 printf("%d", a) 的返回语句?到目前为止,这是我的代码的 sn-p。

    public static int numUnique(int a, int b, int c) {
        if (a==b && a==c) {
            System.out.println("No unique numbers.");
        } else if (a==b && a!=c) {
            System.out.printf("%d%d", a, c);
        } else if (a==c && a!=b) {
            System.out.printf("%d%d", c, b);
        } else if (b==c && b!=a) {
            System.out.printf("%d%d", b, a);
        } else {
            System.out.printf("%d%d%d", a, b, c);
        }
    }
}

我知道那里需要一个 return 语句才能获得正确的语法,并且我想使用 return 类似于我的代码中“理论上”使用的 printf。谢谢!

杰森

【问题讨论】:

  • 但是这个方法不应该返回一个int ...吗?
  • 一个'int'没有格式,甚至没有表示;这只是一个数字。正如@DavidWallace 建议的那样,您可以改为返回一个字符串。

标签: java return printf


【解决方案1】:

如果您正在寻找一个返回String 的方法,您可以使用String.format 方法,它采用与System.out.printf 相同的参数。所以你的问题的代码看起来像这样。

请注意,我已经引入了一些空格来阻止整数一起运行,并且看起来像单个数字。

public static String numUnique(int a, int b, int c) {
    if (a==b && a==c) {
         return "No unique numbers.";
    } else if (a==b && a!=c) {
        return String.format("%d %d", a, c);
    } else if (a==c && a!=b) {
        return String.format("%d %d", c, b);
    } else if (b==c && b!=a) {
        return String.format("%d %d", b, a);
    } else {
        return String.format("%d %d %d", a, b, c);
    }
}

【讨论】:

  • 感谢您的回复。这有助于让事情变得更有意义。老实说,您的版本效果更好,因为我不需要专门返回整数类型与字符串的值。
  • 有一种更短的方法可以实现非常相似的目标。你可以只做类似return new HashSet<Integer>(Arrays.asList(a,b,c)).toString(); 的事情,而不需要所有if/else 的东西。它与您在此处打印的内容不完全相同,但很接近。我没有将其发布为答案,因为它实际上并没有回答您的问题,即使它可能会解决您的问题。
【解决方案2】:

使用return 声明,您将回馈数据。程序(或用户)如何处理这些数据并不是该方法所关心的。

通过格式化操作,您表示数据。只要您拥有正确的数据,您就可以用任何您喜欢的方式来表示它。

所以,严格来说,这是不可能的,除非你想以另一个答案所建议的方式使用String.format

【讨论】:

  • 非常感谢。这实际上帮助我纠正了对这些类型陈述的一些错误信念。
猜你喜欢
  • 2012-11-24
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 2022-08-14
  • 2023-04-01
相关资源
最近更新 更多