这部分代码不起作用。当用户单击 n==0 时,当用户单击 n==1 进入文本字段时,我试图显示保存在文件中的名称。由于某种我无法理解的原因,它出现空白。也许我没有正确调用 savedName 返回值?
if (n == 1){
for(fn=JOptionPane.showInputDialog("What is your first name?");!fn.matches("[a-zA-Z]+");fn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
fn=JOptionPane.showInputDialog("What is your first name?");
}
writeToFile();
for(sn=JOptionPane.showInputDialog("What is your second name?");!sn.matches("[a-zA-Z]+");sn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
sn=JOptionPane.showInputDialog("What is your second name?");
}
if (n == 0){
String fullName = readFromFile();
text.setText("Welcome " + fullName + ".");
System.out.println(fullName);
}
}
private void writeToFile() {
String nameToWrite = fn;
OutputStream outStream = null;
//String savedName = "";
try {
outStream = new FileOutputStream(f);
outStream.write(nameToWrite.getBytes());
//BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
//savedName = br.readLine();
text.setText("Welcome " + fn + ".");
//System.out.println(savedName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.close();
} catch (IOException e) {
// do nothing
}
}
}
//return savedName;
}
private String readFromFile(){
String savedName="";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
savedName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return savedName;
}