I'm not sure how to add a line counter because if I do a while statement such as
while (fileReader.hasNextLine()) {
lines+=1;
file.nextLine();
}
then the rest of my vowels, sentences, etc are set to 0.
my code is:
Scanner input = new Scanner(System. in );
System.out.println("Enter file name: ");
File file = new File(input.nextLine());
if (file.length() == 0) {
System.out.println("The input file is empty.");
System.exit(1);
}
Scanner fileReader = new Scanner(file);
while (fileReader.hasNext()) {
String word = fileReader.next();
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels += 1;
if ((ch == '!' || ch == '.' || ch == '?')) sentences += 1;
if (Character.isLetterOrDigit(ch)) alphaNumeric += 1;
switch (ch) {
case ',':
punctuation += 1;
break;
case '[':
punctuation += 1;
break;
case ']':
punctuation += 1;
break;
case ':':
punctuation += 1;
break;
case '`':
punctuation += 1;
break;
case '-':
punctuation += 1;
break;
case '!':
punctuation += 1;
break;
case '_':
punctuation += 1;
break;
case '(':
punctuation += 1;
break;
case ')':
punctuation += 1;
break;
case '.':
punctuation += 1;
break;
case '?':
punctuation += 1;
break;
case '"':
punctuation += 1;
break;
case ';':
punctuation += 1;
break;
}
}
words += 1;
}
System.out.println("The number of words in the file name: " + words);
System.out.println("The number of lines in the file name: " + lines);
System.out.println("The number of alphanumeric characters " + "in the file name: " + alphaNumeric);
System.out.println("The number of sentences in the file name: " + sentences);
System.out.println("The number of vowels in the file name: " + vowels);
System.out.println("The number of punctuations in the file name: " + punctuation);
Newlines are denoted by the character '\\n'. You could check for instances of that, the same way you are checking for vowels, punctuation, etc.
Use these set of lines
String line = fileReader.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels += 1;
if ((ch == '!' || ch == '.' || ch == '?')) sentences += 1;
if (Character.isLetterOrDigit(ch)) alphaNumeric += 1;
switch (ch) {
// do something
}
}
lines ++;
words += line.split(" ").length;
In your original code, the words were nothing but lines. They were not words as such.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.