0

コードのこのセクションは機能していません。ユーザーが 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;   
}
4

0 に答える 0