java - 返回语句可以像 printf 一样格式化吗?

标签 java return printf

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

    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 语句才能获得正确的语法,并且我想像在我的代码中“理论上”使用的 printf 一样使用 return。谢谢!

杰森

最佳答案

如果您使用的是返回 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);
    }
}

关于java - 返回语句可以像 printf 一样格式化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23461344/

相关文章:

c++ - 是返回 x++ 的行为;定义?

android - 如何让键盘显示返回键?

javascript - 从 JavaScript 中的多个函数返回结果

c - printf 右对齐括号内的数字

c - sizeof() 和 strlen() 之间的区别

java - HDInsight hadoop Java程序无法运行-找不到库

c# - 面向对象游戏编程中的物理

java - AccordionPanel 包含带有选择模式 ="multiple"的数据表

java - Unity 的 GCM 插件,找不到方法 GCMRegistrar.checkDevice

c - 尝试复制有关可变参数的 printf 行为