-1

I am trying to use files that contain long strings of numbers by inputing them as arguments. Then I am trying to find the hamming distance between the two strings. Right now I have errors on lines 7,8,9 and 11. They say "cannot find symbol: method length()." I am very new to java so I am wondering if I am using scanner incorrectly or I messed up somewhere else to cause these errors. Any insight would be appreciated.

If it helps the files I am importing are of the form:

 13413.123,
 12314.434,
 12353.809,

and so on

public static double calcDifference(String[] args) throws IOException {
       Scanner scanner = 
                new Scanner(new File(args[0]));
       Scanner scanner2 = 
                new Scanner(new File(args[1]));
       double a = 0;
       for (double x = 0; x < scanner.length(); x++) {
       for (double y = 0; y < scanner2.length(); y++) {
            if (scanner.charAt(x) == scanner2.charAt(y)) {
                a += 0;
            } else if (scanner.charAt(x) != scanner2.charAt(y)) {
                a += 1;
            }
        }
    }
return a;
}
4

1 回答 1

1

Scanner没有length()(或者chartAt(),正如 Daemon 指出的那样)。

如果您想读取整个文件,不使用任何外部库(例如 Apache)的最短方法是:

String text = new Scanner(new File(args[0])).useDelimiter("$").next();

此外,好的做法是在完成后关闭文件。

Scanner scanner = new Scanner(new File(args[0]));
String text = scanner.useDelimiter("$").next();
scanner.close();

进一步澄清:

现在,您可以使用length()charAt()text$ 是输入结束的正则表达式符号。因此,Scanner只有在输入结束时才停止next()调用。这不是读取整个文件的唯一方法,但它是最短的。

于 2013-11-01T03:10:31.673 回答