我是 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/