扫描仪作为方法参数

时间:2018-04-14 15:01:40

标签: java file

我刚开始用java中的txt文件练习,我有一个问题 - 我需要用扫描仪作为参数制作一个方法,我不知道应该怎么做。此时我没有任何参数就完成了它并且工作正常,但任务是让它成为Scanner。

public static void flipCoins() {
    Scanner scanner = new Scanner(System.in);
    String name = scanner.nextLine();
    File file = new File(name);
    String bufor;

    try {
        scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            int heads = 0;
            int tails = 0;
            int total = 0;
            bufor = scanner.nextLine();
            String[] bufor1 = bufor.split(" ");
            for (int i = 0; i < bufor1.length; i++) {
                bufor1[i] = bufor1[i].toLowerCase();
                if (bufor1[i].equals("h")) {
                    heads++;
                    total++;
                } else if (bufor1[i].equals("t")) {
                    tails++;
                    total++;
                }

            }
            double percent = ((double)heads / (double)total);
            percent = percent * 100;
            percent = Math.round(percent);
            System.out.println(heads + " heads " + "(" + percent + "%).");
            if (heads > tails) {
                System.out.println("There were more heads!");
            }
            System.out.println(" ");
        }
    } catch (FileNotFoundException e) {
        System.err.println("error");
    }
}

谢谢!

0 个答案:

没有答案