输入不起作用

时间:2015-07-04 02:37:18

标签: java input java.util.scanner

我正在编写一个程序来读取文本文件并计算字符数(-c),单词(-w),句子(-s)和段落(-p)。如果我声明了两个字符串(选项和文件名),但是如果我让用户输入值,那么该程序是有效的,它不起作用。我尝试使用(String [] args)和扫描仪,但都不起作用。以下是代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Unit7Lab1 {
    public static void main(String[] args) {
        // String option = args[0];
        // String filename = args[1];
        String option = "-c";
        String filename = "C:\\DrJava\\Sample.txt";
        // Scanner input = new Scanner( System.in );
        // System.out.println("Please enter your option and filename");
        // String option = input.next();
        // String filename = input.next();

        System.out.println(option);
        System.out.println(filename);

        File inFile = new File(filename);
        Scanner sc;

        try {
            sc = new Scanner(inFile);

            if (option == "-c") {
                int nc = CountCharacter(sc);
                System.out.println(nc);
            } else if (option == "-w") {
                int nw = CountWord(sc);
                System.out.println(nw);
            } else if (option == "-s") {
                int ns = CountSentence(sc);
                System.out.println(ns);
            } else if (option == "-p") {
                int np = CountParagraph(sc);
                System.out.println(np);
            }
            sc.close();
        } catch (FileNotFoundException e) {
            System.out.println("Could not find file: " + inFile.getAbsolutePath());
        }
    }

    public static int CountCharacter(Scanner scin) {
        int count = 0;
        while (scin.hasNext()) {
            count += scin.next().length();
        }

        return count;

    }

    public static int CountWord(Scanner scin) {
        int count = 0;
        while (scin.hasNext()) {
            scin.next();
            count += 1;
        }
        return count;
    }

    public static int CountSentence(Scanner scin) {
        String retScin = "";
        while (scin.hasNext()) {
            retScin += scin.next();
        }

        int count = retScin.length() - retScin.replace(".", "").length();
        return count;
    }

    public static int CountParagraph(Scanner scin) {
        int count = 0;
        scin.useDelimiter("\n");
        while (scin.hasNext()) {
            scin.next();
            count += 1;
        }
        return count;
    }
}

0 个答案:

没有答案