I'm trying to finish this code, which iterates through a given file and prints a chart counting the leading ones. However, I get an error for "(47,42): ')' expected" as well as "(47,48): illegal start of expression". The code was working fine (minus skipping comments within lines; which I added the Boolean hasComment and the for, ifs and while loops) Any suggestions would be greatly appreciated.
EDIT I'm still not able to get the program to print, but when I remove the hasComment method and the nested for, if and while loops, it works fine. However, the hasComment method and those loops are suppose to skip comments, but not whole lines. For example, if a line in the file reads "(* comment *) 89", I need to skip the comment but read 89. Any pointers or guidance would be great, thanks!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Benford {
public static boolean hasComment(String s) {
return s.indexOf("(*") != -1 && s.indexOf("*)") != -1;
}
// Reads file and creates array
private static int[] countDigits(Scanner input) {
int[] count = new int[10];
while (input.hasNextInt()) {
int n = input.nextInt();
count[firstDigit(n)]++;
}
return count;
}
// Display chart
private static void reportResults(int[] count) {
System.out.println("Digit Count Frequency");
for (int i = 1; i < count.length; i++) {
double freq = count[i] * .10;
System.out.printf("%-5d %-5d %.2f\n", i, count[i], freq);
}
}
// Returns first digit
private static int firstDigit(int n) {
int result = Math.abs(n);
while (result >= 10) {
result = result / 10;
}
return result;
}
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.print("Enter a file name: ");
String name = in.nextLine();
Scanner input = new Scanner(new File(name));
int[] count = countDigits(Scanner input);
for (int i = 0; i < 10; i++) {
if (!input.hasNext()) {
break;
}
// else
String line = input.next();
String s = " ";
if (hasComment(line)) {
int endCommentIndex = line.indexOf("*)");
line = line.substring(endCommentIndex + 2);
}
while (line.charAt(0) == ' ') {
s = s.replaceAll("\\s+", "");
}
reportResults(count);
}
}
}