0

ユーザーから収集したデータのデータベースとしてテキストファイルを使用しようとしています。これは、使用しているコンストラクターです。

public DatabaseOperations(String name,double newWeight) throws FileNotFoundException, ParseException{
    f= new File (removeSpaces(name)+".txt");
    if (!f.exists()){
        System.out.println("This user dosen't exist");
        return;
    }
    try {
        out= new PrintWriter (f);
    } catch (FileNotFoundException e) {
        System.out.println("Error, You don't say");
    }
    // This section is used to initialize a new object from Customer with values in the excising file
    cust = new Customer();
    in=new Scanner(f);
    in.next();
    in.next();
    cust.setName(in.next());
    in.next();
    in.next();
    in.next();
    cust.setStartingDate(in.next());
    in.next();
    in.next();
    cust.setAge(Integer.parseInt(in.next()));
    in.next();
    in.next();
    in.next();
    cust.setStartingWeight(Double.parseDouble(in.next()));
    in.next();
    in.next();
    cust.setHeight(Double.parseDouble(in.next()));
    in.next();
    in.next();
    in.next();
    cust.setBMI(Double.parseDouble(in.next()));
    in.next();
    in.next();
    in.next();
    cust.setTargetWeight(Double.parseDouble(in.next()));
    in.next();
    in.next();
    in.next();
    cust.setTargetDate(in.next());
    //----------------------------------------------------------------
    // check this for errors !!!
    cust.setWeight(newWeight);
    out.println(form.format(cust.getCurrentDate())+"\t"+df.format(cust.getWeight())+"\t\t"+cust.getBMI()+"\t\t"+cust.percentDone()+"\t"+cust.timePassed());
    out.close();
}

これらの多くのin.next()は、不要なデータをスキップするために使用されます。使用しているファイルの構造は次のようになります。

Name :kkkk  Started at :06/12/2012
Age :19 Starting Weight :85.0
Height :1.86        Starting BMI :24.57
Target Weight :75.5 Target Date :15/12/2012

問題は、コンパイラがNoSuchElementExceptionをスローし、最初の(in.next())を指すことです。別の問題は、このコンストラクタを呼び出すとすぐにファイルが空になることです。

4

2 に答える 2

0
String name,date,age,wight,height,....;
LineNumberReader  lnr = new LineNumberReader(new FileReader(new File("File1")));
lnr.skip(Long.MAX_VALUE);
List<String> list = new ArrayList<String>();
while(file.hasNextLine()) {
String str = file.nextLine();
String[] str1 = str.split(" ");
list.add(str1[1]);
list.add(str1[str1.length() - 1]);
}
cust.setAge(list.get(0));
.....
.....
于 2012-12-07T09:47:47.203 に答える
0

java.util.Propertiesデータベースの代わりにテキストファイルを使用する場合は、このクラスを使用することを強くお勧めします。を使用する必要はありませんnext()。キーと値のペアでこれを解決できます:http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html

Properties prop = new Properties();

try {
  prop.load(new FileInputStream(removeSpaces(name)+".txt"));
  cust.setAge(Integer.parseInt(prop.getProperty("age")));
} catch (IOException e) {
  e.printStackTrace();
}

プロパティのテキストファイルは次のようになります

age=19
name=kkkk
started_at=06/12/2012
starting_weight=85.0
于 2012-12-07T09:47:58.787 に答える