複数のパラメータでカスタムオブジェクトを作成する際に問題を解決しようとしていますが、パラメータはまずScanner
を使用して1つずつ見つけなければなりません。すべてのパラメータを読み込むまで、オブジェクトの作成をどのように遅らせることができますか?
基本的には、各行が複数の属性(名前、犯罪インデックスなどの郡)を持つ新しいオブジェクトを表す入力ファイルがある場合、whileループを使用してScanner
をスキャンしています入力ファイルを1行ずつ入力し、ループ内で別のwhileループを使用していて、Scanner
という新しい文字列をスキャンします。そうすれば、私はオブジェクトのすべての属性を分離し、それらの値すべてをコンストラクタに渡すことでオブジェクトを作成できます。
私が理解できないことは、入力ファイル内のすべての行がオブジェクトになり、その行のすべての単語を持つため、各行にすべての単語があるまで、オブジェクトの作成を遅らせる方法ですオブジェクトのパラメータとして使用されます。
これはどのように効果的に配列や何かのようなすべての単語を格納することなく行うことができます知っていますか?
public CountyItem(String countyName, String countyState, double countyPercentageClintonVoters, double countyResidentMedianAge,
int countyResidentMeanSavings, int countyPerCapitaIncome, double countyPercentageBelowPovertyLevel,
double countyPercentageVeterans, double countyPercentageFemale, double countyPopulationDensity,
double countyPercentageLivingInNursingHomes, int countyCrimeIndexPerCapita){
itemCountyName = countyName;
itemCountyState = countyState;
itemCountyPercentageClintonVoters = countyPercentageClintonVoters;
itemCountyResidentMedianAge = countyResidentMedianAge;
itemCountyResidentMeanSavings = countyResidentMeanSavings;
itemCountyPerCapitaIncome = countyPerCapitaIncome;
itemCountyPercentageBelowPovertyLevel = countyPercentageBelowPovertyLevel;
itemCountyPercentageVeterans = countyPercentageVeterans;
itemCountyPercentageFemale = countyPercentageFemale;
itemCountyPopulationDensity = countyPopulationDensity;
itemCountyPercentageLivingInNursingHomes = countyPercentageLivingInNursingHomes;
itemCountyCrimeIndexPerCapita = countyCrimeIndexPerCapita;
}
そして:ここ
は、すべての適切な順序である行の言葉のすべてを取り、入力ファイルの各行の新しいオブジェクトを作成するオブジェクトのクラスからのコンストラクタですここで私のプログラムの主な方法(まだ未完成ですが)は、入れ子のwhileループと2つの別々のスキャナを使用して、入力ファイルのすべての行とその行のすべての行を最初に読み込むという私の計画を示しています。public static void main(String[] args) throws IOException{
//Scanner and FileWriter
Scanner inFile = new Scanner(new FileReader("data/test1.txt")); //change this to use different test .txt file
FileWriter outFile = new FileWriter("data/output.txt");
//loops through each line in inputl.txt until end is reached
while(inFile.hasNextLine()){
String line = inFile.nextLine();
Scanner lineScanner = new Scanner(line);
//loops through every word in a given line
while(lineScanner.hasNext()){
}
lineScanner.close();
}
inFile.close();
}
ビルダーパターン - http://www.tutorialspoint.com/design_pattern/builder_pattern.htmlを参照してください。 – RamanSB
作成するCountyItemは変更できない必要があります。このため、パラメータが非常に多いので、Builderパターンを使用することをお勧めします。ビルダを使用すると、オブジェクトのすべてのデータを組み立てるまで、オブジェクトはインスタンス化されません。 – scottb
*メソッド/コンストラクタのパラメータがたくさんある場合は、ビルダーパターンを使用するか、関連するパラメータをクラスに分解して最上位の「CountyItem」に組み込むことでデザインを改善する必要があります。 –