基本上,我正在测试从文件中保存/读取并使一个DetailsManager类与“Details.txt”进行通信。
save();
方法应该接受输入,将它们写入文件,并更新属性。当给定“0”作为年龄输入时,它被正确放入文本文件中并从save();
内打印出this.age将给出“0”。
然后,当我尝试通过getAge();
或从另一个类直接调用Dets.Age;
时获取值时,它会发出“48”,ASCII为“0”,而不是“ 0" 。
即使从getAge();
打印也会返回“48”。为什么会这样做,我该如何解决?
代码:
package mainpack;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class DetailsManager {
private String fileName = "Details.txt";
String usrname = "Guest";
private int age = 0;
private char ds ='f';
Boolean dontshow = false;
public int getAge() {
System.out.println("THE AGE IS:"+this.age);// THIS ONE PRINTS 48
return age;
}
public void refresh() {
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
usrname = bufferedReader.readLine();
age = bufferedReader.read();
ds = (char) bufferedReader.read();
if(ds == 't')dontshow = true;
else dontshow = false;
bufferedReader.close();
} catch (FileNotFoundException ex1) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
}
public void save(String usrname, Integer age, boolean dontshow) {
this.usrname = usrname;
this.age = age;
this.dontshow = dontshow;
if(dontshow == true) this.ds = 't';
else this.ds = 'f';
System.out.println("THE AGE2 IS:"+this.age);// THIS ONE PRINTS 0
PrintWriter printWriter;
try {
printWriter = new PrintWriter("./Details.txt");
printWriter.println(this.usrname);
printWriter.println(this.age);
printWriter.println(this.ds);
printWriter.close();
} catch (FileNotFoundException e) {
System.out.println("File not found. Someone was messing with my files again..");
}
}
}
这就是“Details.txt”的样子:
Guest
0
f
答案 0 :(得分:0)
您的问题不在getAge方法中。如果您自己尝试并创建类的新实例,并在之后调用getAge(),您将看到返回正确的值。
如果在使用refresh()或save()方法修改它后,它返回42,这意味着它是*的ASCII值。你的文件Details.txt中有*吗?如果这对您没有帮助,我们能看到您的主要方法吗?