2014-12-04 86 views
1

這是我的代碼我需要用java

/* 
 
* To change this license header, choose License Headers in Project Properties. 
 
* To change this template file, choose Tools | Templates 
 
* and open the template in the editor. 
 
*/ 
 

 
package namereader; 
 
import java.util.*; 
 
import java.io.*; 
 
/** 
 
* 
 
* @author jpowell1225 
 
*/ 
 
public class NameReader { 
 

 
    /** 
 
    * @param args the command line arguments 
 
    */ 
 
    public static void main(String[] args) throws IOException{ 
 
     // TODO code application logic here 
 
     boolean onoff = true; 
 
     int count = 0; 
 
     int count2 = 0; 
 
     String first = null; 
 
     FileWriter fw = new FileWriter("txt",true); 
 
     
 
     String last = null; 
 
     
 
     Scanner scan = new Scanner(System.in); 
 
     scan.useDelimiter(" "); 
 
     //scan.useDelimiter(); 
 
     while(onoff){ 
 
      first = scan.nextLine(); 
 
      
 
      if(first.equals("quit")){ 
 
        break; 
 
       } 
 
      
 
     
 
       
 
       fw.write(first); 
 
       FileReader fr = new FileReader("txt"); 
 
       Scanner src = new Scanner(fr); 
 
       count = first.lastIndexOf(" "); 
 
       count2 =first.indexOf(" ", 2); 
 
       System.out.println("Your name is: " + first.substring(count) + " " + first.substring(count2, count2+2) + ". " + first.substring(0, count2)); 
 
    
 
     } 
 
     fw.close(); 
 
     scan.close(); 
 
     
 
      
 
    } 
 
    
 
}

雖然它正確地輸出輸入名稱(從中間名姓切換它姓名中間初始)寫一個文件,它確實創建了一個名爲「txt」的文件,每當我打開文件時它都是空的。

我需要能夠在文件「txt」中添加多個輸入。 TIA

回答

0

你忘了自動flush()輸出流,因爲這

fw.flush();//flush it before close it. 
fw.close(); 

您也可以使用try(<<Closable>>){},讓Java的關閉(FileWriter)它。

編輯
try(<<closable_0>>;<<closable_1>>;...){}是因爲java1.7一個新的方案,它的使用爲讓JVM只是塊後自動關閉closable對象。在你的代碼中可能是這樣的。

try(Scanner scan = new Scanner(System.in);FileWriter fw = new FileWriter("txt",true);){ 
//using the objects 
}//jre will closes both :scan and :fw objects automatically 
+0

使用fw.flush()我沒有做任何事情,但你能告訴我如何格式化我的代碼的方式,我可以使用try {}(我在這個對於新手:P ) – 2014-12-04 22:41:46

+0

檢查編輯@JacobPowell – 2014-12-04 22:48:03