![](/img/trans.png)
[英]Can someone help me to figure out how to read my file from ":" (not included) til the end of the line?
[英]Can someone help me add a line counter to my code when I read this file
我不確定如何添加行計數器,因為如果執行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);
換行符用字符'\\ n'表示。 您可以像檢查元音,標點符號等一樣檢查實例。
使用這些線
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;
在您的原始代碼中,單詞不過是行。 他們不是這樣的話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.