-5

I have the following problem... I need to compare two string and output the first one if they are not equal. Something like the code below, but printing the first string instead. How can I do it?

String myString1 = new String("abc123");
String myString2 = new String("abc");
if(myString1.equals(myString2))
{
    System.out.println("The two strings are equal");
}
else 
{
    System.out.println("The two strings are not equal");
}
4

2 回答 2

2

您可以将第一个字符串作为参数传递给System.out.println,如下所示:

if(myString1.equals(myString2)) {
  System.out.println("The two strings are equal");
}
else {
  System.out.println(myString1);
}
于 2013-05-07T21:41:41.283 回答
0

您可以使用三元运算符:

String myString1 = new String("abc123");
String myString2 = new String("abc");
System.out.println("The two strings are " +
  (myString1.equals(myString2) ? "" : "not") + " equal";

你也可以使用String.format它。

于 2013-05-08T02:47:07.093 回答