// trying to find whether two string match after toUppercase operation
//在toUppercase操作后尝试查找两个字符串是否匹配
package testapp1;
public class TestApp1
{
public static void main(String[] performing_a_simple_for_loop)
{
String firstName = "John";
char fname[] = {'J','O','H','N'};
System.out.println(firstName.toUpperCase());
String name2;
name2 = firstName.toUpperCase();
if(fname.equals(name2))
{
System.out.println("True");
}
else
{
System.out.println("False");
}
}
}
2 个解决方案
#1
2
fname
is an array, so can not be directly compared to a String
fname是一个数组,因此无法直接与String进行比较
You can do
你可以做
if(new String(fname).equals(name2))
#2
1
this is the reason why is always printing false
这就是为什么总是打印错误的原因
fname.equals(name2)
you are comparing a String against an array...
你正在比较一个字符串与数组...
that return false because they are not the same data type
返回false,因为它们不是相同的数据类型
imagine if I do:
想象我是否这样做:
"1".equals(1)
yes, both are holding somehow the same information, but that is not enough in java to say they are equal...
是的,两者都以某种方式持有相同的信息,但这在java中并不足以说它们是平等的......
so what you can do:??? you need to convert one type into the other...
所以你能做什么:???你需要将一种类型转换为另一种类型......
// option 1: char[] -> string
System.out.println(new String(fname).equals(firstName.toUpperCase()));
// option 2: string -> char[]
System.out.println(Arrays.equals(firstName.toUpperCase().toCharArray(), fname));
and as you see, for comparing arrays you may need the Array.equals() method
如您所见,为了比较数组,您可能需要Array.equals()方法
#1
2
fname
is an array, so can not be directly compared to a String
fname是一个数组,因此无法直接与String进行比较
You can do
你可以做
if(new String(fname).equals(name2))
#2
1
this is the reason why is always printing false
这就是为什么总是打印错误的原因
fname.equals(name2)
you are comparing a String against an array...
你正在比较一个字符串与数组...
that return false because they are not the same data type
返回false,因为它们不是相同的数据类型
imagine if I do:
想象我是否这样做:
"1".equals(1)
yes, both are holding somehow the same information, but that is not enough in java to say they are equal...
是的,两者都以某种方式持有相同的信息,但这在java中并不足以说它们是平等的......
so what you can do:??? you need to convert one type into the other...
所以你能做什么:???你需要将一种类型转换为另一种类型......
// option 1: char[] -> string
System.out.println(new String(fname).equals(firstName.toUpperCase()));
// option 2: string -> char[]
System.out.println(Arrays.equals(firstName.toUpperCase().toCharArray(), fname));
and as you see, for comparing arrays you may need the Array.equals() method
如您所见,为了比较数组,您可能需要Array.equals()方法