charAt()调用中的StringIndexOutOfBoundsException

时间:2015-11-07 01:21:52

标签: java file char indexoutofboundsexception

我是编码的新手,我正在尝试制作一个匹配两个文本文件的程序。对于第一行,我匹配第一个字符,第二行匹配两个字符,依此类推,直到其中一个文件结束。

这是问题所在。如果该行没有足够的字符,则只比较存在的字符,如果两行99都有"abc",那么它将被视为匹配。

如果没有抛出错误,我似乎无法满足此要求,因为如果字符数少于行数,charAt()正在读取空值。谢谢您的帮助!

代码:

public static void main(String[] args) throws IOException
{
    boolean flag;
    File f = new File(args[0]);
    Scanner sc = new Scanner(f);
    File f2 = new File(args[1]);
    Scanner sc2 = new Scanner(f2);
    int line = 1;
    String t1 = "";
    String t2 = "";
    String work = "";

    while(sc.hasNext() && sc2.hasNext())
    {
        String line1 = sc.nextLine().toUpperCase();
        String line2 = sc2.nextLine().toUpperCase();
        line1 = line1.trim();
        line2 = line2.trim();
        for(int i = 0; i < line; i++)
        {
            if(line1.charAt(i) != line2.charAt(i))
            {
                work = "no";
                t1 = Character.toString(line1.charAt(i));
                t2 = Character.toString(line2.charAt(i));
            }
            else
            {
                work = "";
                t1 = Character.toString(line1.charAt(i));
                t2 = Character.toString(line2.charAt(i));
            }
        }
        if(work == "")
        {
            System.out.println("Line # " + line + ": Matching " + line + " character/s true " + "**" + line1 + "**" + " and " + "**" + line1 + "**");

        }
        else
        {
            System.out.println("Line # " + line + ": Matching " + line + " character/s false " + "**" + line1 + "**" + " and " + "**" + line2 + "**");
        }
        line += 1;
    }
}

2 个答案:

答案 0 :(得分:0)

您需要检查line1和line2与i变量的长度,然后在行的最后一个字母末尾调用char。

if(line1.length()&lt; i)

之类的东西

String.length()

答案 1 :(得分:0)

首先检查两条线的长度是否相等(并将变量work更改为boolean而不是String)。它有助于提高性能,因为boolean需要1个字节且比String多。{/ p>

if (line1.length() > line2.length()) {
    work = false;
} else if (line1.length() < line2.length()) {
    work = false;
} else if (line1.charAt(i) != line2.charAt(i)) {
    work = false;
} else {
    work = true;
}

或者:

if (line1.length() != line2.length()) {
    work = false;
} else {
    work = true;
}

或者:

if (line1.length() == line2.length()) {
    work = true;
} else {
    work = false;
}

然后

if(work) {//This is the same as if (work == true)
    System.out.println("Line # " + line + ": Matching " + line + " character/s true " + "**" + line1 + "**" + " and " + "**" + line1 + "**");
} else {
    System.out.println("Line # " + line + ": Matching " + line + " character/s false " + "**" + line1 + "**" + " and " + "**" + line2 + "**");
}

但是,如果您确实需要/需要将work变量用作String,请不要将其与==进行比较,但要work.equals("")"".equals(work)(第二个阻止NullPointerException

详细了解.equals()Java == vs equals()How do I compare Strings in Java。关于"".equals(variable) vs variable.equals("")

如果在任何位置,2行与任何字母不匹配,您可能还需要breakcontinue