私は、戻り値を使用しようとしていますfileName
メソッドからfile()
メソッドに、nGram()
私はnグラムにファイルの内容を解析することができるように。これを行うための作業コードがありますが、2つの別々のメソッドが必要です。
package ie.gmit.sw;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Example {
private String fileName;
private int k;
public Example(String fileName, int k) {
this.fileName = fileName;
this.k = k;
}
public String file(String fileName) throws IOException {
//Open the file.
FileReader fr = new FileReader(fileName);
Scanner inFile = new Scanner(fr);
// Read lines from the file till end of file
while (inFile.hasNext()) {
// Read the next line.
String line = inFile.nextLine();
// Display the line.
System.out.println(line);
}
// Close the file.
inFile.close();
return fileName;
}
private void nGram() throws IOException{
List<String> ngrams = new ArrayList<>();
for (int i = 0; i <= fileName.length() - k; i++) {
ngrams.add(fileName.substring(i, i + k));
}
System.out.println(ngrams);
}
//Working
// private static void run() throws FileNotFoundException {
// // Open the file.
// FileReader fr = new FileReader(fileName);
// Scanner inFile = new Scanner(fr);
//
// // Read lines from the file till end of file
// while (inFile.hasNext()) {
// // Read the next line.
// String line = inFile.nextLine();
// // Display the line.
// System.out.println(line);
//
// List<String> ngrams = new ArrayList<>();
// for (int i = 0; i <= line.length() - k; i++) {
// ngrams.add(line.substring(i, i + k));
// }
// System.out.println(ngrams);
// }
//
// // Close the file.
// inFile.close();
// }
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter file: ");
String fileName = scanner.nextLine();
System.out.println("Enter kmers: ");
int k = scanner.nextInt();
scanner.close();
Example e = new Example(fileName, k);
e.file(fileName);
e.nGram();
}
}
出力
Hello world
Good Day okay
random text saying anything me laptop bye
[sa, am, mp, pl, le, e., .t, tx, xt]
file()から返された値を取得するには、nGramパラメータで文字列を渡し、その中でfile(string)を呼び出すだけです(file()はすでに文字列を返すため)。
private String file(String fileName){...}
private void nGram(String valueFromFile){...}
public static void main(String[] args) throws Exception {
...
Example e = new Example(fileName, k);
e.nGram(e.file(fileName));
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加