return语句可以格式化为printf吗?

jgi*_*pie 1 java printf return

我是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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道在那里需要一个返回语句以获得正确的语法,并且我想使用类似于在我的代码中"理论上"使用的printf的返回.谢谢!

贾森

Daw*_*ica 6

如果您正在String使用返回a 的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);
    }
}
Run Code Online (Sandbox Code Playgroud)