我正在尝试比较2个字符串。我先使用split方法,然后再使用toCharArray
方法。
毕竟我使用了等于,但最后我得到了:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException"
import java.util.Scanner;
public class LoopsWiederholung {
public static void main (String [] args){
System.out.print("Enter the first String : ");
Scanner scan1 = new Scanner(System.in);
String s1 = scan1.next();
s1.toUpperCase();
System.out.print("Enter the second String : ");
String s2 = scan1.next();
s2.toUpperCase();
String[] s3 = new String[100];
s3 = s1.split("\\ ");
String[] s4 = new String[100];
s4 = s2.split("\\ ");
for (int i = 0 ; i< 100 ; i++){
if( s3[i].toCharArray().equals(s4[i].toCharArray())){
System.out.print(s3[i]);
}
}
}
}
答案 0 :(得分:0)
这么多错误,所以在注释中找到我的代码
System.out.print("Enter the first String : ");
Scanner scan1 = new Scanner(System.in);
String s1 = scan1.next();
s1 = s1.toUpperCase(); // Strings are immutable
System.out.print("Enter the second String : ");
String s2 = scan1.next();
s2 = s2.toUpperCase();
// first check the lengths
if (s1.length() != s2.length()) {
System.out.println("not the same");
return;
}
String[] s3 = s1.split(""); // use this pattern
String[] s4 = s2.split("");
for (int i = 0 ; i< s3.length ; i++){
if (s3[i].equals(s4[i]))
System.out.print(s3[i]);
}
}
我认为您是split
来获取Strings
的数组,还是使用toCharArray()
来比较chars
答案 1 :(得分:0)
for循环从0迭代到99,但是它假定该数组中有99个元素,因此,如果没有,您会看到ArrayIndexOutOfBoundsException。
一种解决方法可能是更改:
String[] s3 = s1.split("\\ ");
和
String[] s4 = s2.split("\\ ");
以便将for循环更改为:
for (int i = 0 ; i< s3.length(); i++){
if(s3[i].equals(s4[i])){
System.out.print(s3[i]);
}
}
如@Scary Wombat所述,使用string1.equals(string2)
比较两个字符串比检查字符数组更容易。