【发布时间】:2020-10-05 18:21:50
【问题描述】:
我是java初学者。我开发了一个 Java 代码来比较两个用户输入的字符串是否包含相同频率的相似字符并将它们打印到屏幕上。但它在编译过程中显示运行时错误( ArrayOutOfBoundException )。帮我找出错误。
import java.util.Scanner;
public class Checker {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String x = scan.next();
String y = scan.next();
boolean anws = similarCharctr(x, y);
System.out.println( (anws) ? "Similar" : "Dissimilar" );
}
static boolean similarCharctr(String x, String y) {
boolean status = false;
if(x.length() == y.length()){
status = false;
}
String e = x.toUpperCase();
String f = y.toUpperCase();
char c [] = new char[e.length()];
char d [] = new char[f.length()];
for(int i = 0; i<c.length; i++){
c[i] = e.charAt(i);
d[i] = f.charAt(i);
}
for(int j = 0; j< (c.length - 1); j++){
for(int i = 0; i< c.length; i++){
if( c[j] >c[i+1])
{
char temp;
temp = c[j];
c[j] = c[i+1];
c[i+1] = temp;
char temp1;
temp1 = d[j];
d[j] = d[i+1];
d[i+1] = temp1;
}
}
}
for(int i = 0; i< c.length; i++){
if(c[i] == d[i]){
status = true;
}
else{
status = false;
}
}
return status;
}
}
【问题讨论】:
-
您需要考虑
c和d的长度——它们可能不同。这适用于所有循环。顺便提一句。您的变量命名很糟糕 - 想出一些有意义的名称,我不知道该代码中发生了什么。 -
@Reznik 与问题无关。
-
这个
c[j] >c[i+1]是导致exception的原因。当循环时出现i = c.length -1条件时,它会尝试评估c[c.lenght]并因此产生异常。
标签: java arrays string sorting runtime-error