嘿我正在编写一个计算文本文件的单词,句子,元音,字符等的程序。我想使用toString()来连接所有类和结尾并以格式返回它们:{filename}:{character count} c {vowel count} v {word count} w {line count} l {sentence count }秒。我遇到了int类的问题。前(charCount.toString())'c'
+ ....这是我的代码到目前为止。谢谢
import java.io.FileInputStream;
public class TextFileAnalyzer {
public static void main(String[] args) {
try {
TextFileAnalyzer mytfa = new TextFileAnalyzer("/Users/patrickmro/Desktop/text.txt");
System.out.println(mytfa.getCharCount());
System.out.println(mytfa.getSentenceCount());
System.out.println(mytfa.getLineCount());
System.out.println(mytfa.getVowelCount());
}
catch (Exception e) {
}
}
// You'll probably want some private fields
private java.lang.String filePath;
private int sentenceCount;
private int wordCount;
private int charCount;
private int lineCount;
private int vowelCount;
private java.lang.String textString;
/**
* Constructs a new TextFileAnalyzer that reads from the given file. All file
* I/O is complete once this constructor returns.
* @param filePath a path to the file
* @throws Exception if any errors are generated by the Java API while reading
* from the file
*/
public TextFileAnalyzer(String filePath) throws Exception {
// This is your job...
this.filePath = filePath;
charCount = 0;
int prevChar = -1;
FileInputStream input = new FileInputStream(filePath);
for(int c = input.read(); c != -1 ; c = input.read()) {
charCount++;
if (c == '.' && prevChar != '.') {
sentenceCount++;
}
if(c == '\n') {
lineCount++;
}
if(Character.isWhitespace(c) && (prevChar != -1 || !Character.isWhitespace(prevChar) )) {
wordCount++;
}
prevChar = c;
if(c == 'A' || c == 'E' || c == 'I'|| c == 'O' || c == 'U') {
vowelCount++;
}
if(c == 'a' || c == 'e' || c == 'i'|| c == 'o' || c == 'u') {
vowelCount++;
}
}
lineCount++;
input.close();
}
/**
* Returns the number of single-byte characters in the file, including
* whitespace.
*
* @return the number of characters in the file
*/
public java.lang.String getfilePath() {
return this.filePath;
}
public int getSentenceCount() {
return sentenceCount ;
}
public int getWordCount() {
return wordCount ;
}
public int getCharCount() {
return charCount ;
}
public int getLineCount() {
return lineCount ;
}
public int getVowelCount() {
return vowelCount;
}
public java.lang.String toString() {
// {filename}: {character count}c {vowel count}v {word count}w {line count}l {sentence count}s
return (this.getfilePath())':' + (sentenceCount.toString())'s' + (wordCount.toString())'w';
}
}
答案 0 :(得分:2)
更简单的一个:更改此方法如下,它将起作用(由于字符串连接,在此期间非字符串会自动转换为字符串。
public java.lang.String toString() {
return this.getfilePath() + ":" + sentenceCount + "s" + wordCount + "w";
}
或者,将int
(这是整数的原始数据类型,因此没有类似toString()
的方法)替换为Integer
(这是一个整数的Java类,将原始int
包装在其中,因为它是一个类,它在代码中的任何地方都有toString()
}这样的方法,你会很好。
例如替换:
private int sentenceCount;
使用:
private Integer sentenceCount;
同时将方法的返回类型从int
更改为Integer
。
答案 1 :(得分:1)
int是Java中的基本类型,因此没有与之关联的方法。但是,您不需要使用toString()
,这应该可以正常工作
return this.getfilePath() +':' + sentenceCount + 's' + wordCount + 'w';