期望:用戶輸入自己的名字後進行游戲, 游戲完成後會得到一個double類型的分數, 然後把名字和分數寫入txt檔,最後讀取txt檔的資料使用arraylist對分數進行排名,然後輸出.
目前的進度是這樣的
public class abc{
private String usersname;
private double scores;
public String getusername() {
return usersname;
}
public void setusername(String usersname) {
this.usersname = usersname;
}
public double getscore() {
return scores;
}
public void setscore(double scores) {
this.scores = scores;
}
public abc(){
}
public abc(String username,double score){
usersname = username;
scores = score;
}
}
import java.io.*;
public class rw_txt {
public static void main(String[] args) throws IOException {
abc s = new abc();
File fw = new File("a.txt");
FileOutputStream fop = new FileOutputStream(fw,true);
OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
writer.append(s.getusername());
writer.append("\t");
writer.append(s.getscore()); <---此處報錯
writer.close();
fop.close();
FileInputStream fip = new FileInputStream("a.txt");
InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
StringBuffer sb = new StringBuffer();
while (reader.ready()) {
sb.append((char)reader.read());
}
System.out.println(sb.toString());
reader.close();
fip.close();
}
}
望大神請教TvT 小的剛學java沒多久,腦袋實在轉不過來了
由於append需要「文字」型態參數而非「數字」
所以要先把 double 轉成 string
writer.append(s.getscore());
改成
writer.append(Double.toString(s.getscore()));
樓上已經點出問題
補充的偷懶的寫法writer.append("" + s.getscore());
另外您 getter 與 setter 的命名不佳
與 field 不一致
值域:usersname
方法:username
值域:scores
方法:score
沒有駝峰
getusername → getUsername
setusername → setUsername
getscore → getScore
setscore → setScore
要手Key就要Key對
不然就使用IDE自動生成