2014-05-04 54 views
1

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

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在我的代码中使用了“理论上”。谢谢!

杰森

+1

但不应该这个方法返回一个int ...? – sfletche

+0

'int'没有格式,甚至没有表示;这只是一个数字。正如@DavidWallace所示,您可以返回一个字符串。 – davmac

回答

4

如果你是一个返回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); 
    } 
} 
+0

感谢您的回复。这有助于事情更有意义。实际上,你的版本效果更好,因为我不需要特别返回整数类型的值。 – jgillespie

+0

有一个简短的方法来实现非常相似的东西。你可以做一些像'return new HashSet (Arrays.asList(a,b,c))。toString();'没有所有'if/else'的东西。这与你在这里打印的东西不完全一样,但它很接近。我没有把它作为答案发布,因为它并没有真正回答你的问题,即使它可以解决你的问题。 –

1

随着return声明,你回馈数据。程序(或用户)如何处理该数据并不是该方法的关注点。

使用格式化操作,您的代表数据。只要你有正确的数据,你可以用你喜欢的任何方式表示它。

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

+0

非常感谢。这实际上帮助我解决了关于这些类型的陈述的一些错误观念。 – jgillespie

相关问题