我不知道如何添加行计数器,因为如果我执行一些while语句,例如
while (fileReader.hasNextLine()) {
lines+=1;
file.nextLine();
}
然后我的其余元音,句子等都设置为0.
我的代码是:
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);
答案 0 :(得分:1)
换行符由字符'\ n'表示。你可以检查它的实例,就像检查元音,标点符号等一样。
答案 1 :(得分:0)
使用这些行
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;
在原始代码中,单词只是行。他们不是这样的话。