I am writing a program that reads a text file and counts either the number of characters (-c), words (-w), sentences (-s), and paragraphs (-p). The program works if I declare the two strings (option and filename) but if I have the user input the values, it doesn't work. I've tried using (String [] args) and a Scanner but neither works. Below is the code:
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;
}
}