数组非法启动

时间:2017-02-01 21:31:54

标签: java

我正在尝试完成此代码,该代码遍历给定文件并打印一个计算前导图表的图表。但是,我得到一个错误“(47,42):')'预期'以及”(47,48):非法开始表达“。代码工作正常(减去跳过行内的注释;我添加了布尔hasComment和for,ifs和while循环)任何建议都将非常感谢。

编辑我仍然无法打印程序,但是当我删除hasComment方法和嵌套for,if和while循环时,它工作正常。但是,hasComment方法和那些循环假设跳过注释,但不是整行。例如,如果文件中的一行显示“(* comment *)89”,我需要跳过评论,但请阅读89.任何指针或指导都会很棒,谢谢!

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);

      }

  }

}

1 个答案:

答案 0 :(得分:1)

你在这里遇到了问题。

  Scanner input = new Scanner(new File(name));

  int[] count = countDigits(Scanner input);

相反,你应该只传递参考。

 Scanner input = new Scanner(new File(name));
 int[] count = countDigits(input);

这是不允许的,

中的scape序列“\ s +”
s = s.replaceAll("\s+", "");

有效的是\ b \ t \ n \ f \ r \“\'\