2012-01-24 41 views
2

我需要創建一個基本的程序來輸入文本到一個.txt文檔,所以我創建了這個,但我不明白爲什麼第一個問題會在程序第一次運行時被跳過。爲什麼我的第一個.nextline在循環中跳過,然後下次不跳過?如何阻止它被覆蓋?

如果第一個設置循環的問題不存在,就不會發生這種情況。另外,如何在我想要的時候覆蓋txt文檔中已存在的內容,從而避免它被添加到文檔中。

到目前爲止,最後一種方法似乎工作得很好,但我還是認爲我仍然會包括它。

package productfile; 
import java.io.*; 
import java.util.Scanner; 

/** 
* 
* @author Mp 
*/ 
public class Products { 

public void inputDetails(){ 
int i=0; 
int count=0; 
String name; 
String description; 
String price; 

Scanner sc = new Scanner(System.in); 

System.out.println("How many products would you like to enter?"); 
count = sc.nextInt(); 

do{ 
    try{ 

     FileWriter fw = new FileWriter("c:/Users/Mp/test.txt"); 
     PrintWriter pw = new PrintWriter (fw); 

     System.out.println("Please enter the product name."); 
     name = sc.nextLine(); 
     pw.println("Product name: " + name); 

     System.out.println("Please enter the product description."); 
     description = sc.nextLine(); 
     pw.println("Product description: " + description); 

     System.out.println("Please enter the product price."); 
     price = sc.nextLine(); 
     pw.println("Product price: " + price); 

     pw.flush(); 
     pw.close(); 

     i++; 

    }catch (IOException e){ 
     System.err.println("We have had an input/output error:"); 
     System.err.println(e.getMessage()); 
     } 
    } while (i<count); 
} 

public void display(){ 
    String textLine; 
try{ 

     FileReader fr = new FileReader("c:/Users/Mp/test.txt"); 
     BufferedReader br = new BufferedReader(fr); 
     do{ 
      textLine = br.readLine(); 
      if (textLine == null){ 
       return; 
      } else { 
       System.out.println(textLine); 
      } 
     } while (textLine != null); 
    }catch(IOException e){ 
     System.err.println("We have had an input/output error:"); 
     System.err.println(e.getMessage()); 
    } 
} 
} 

回答

0

.nextInt()不會收到您的輸入新聞。你需要在它之後放置一個空白的.nextLine()。

1

當您爲nextInt()輸入int時,您還要按回車鍵以輸入要接收的數據,這意味着要讀取的新數據行也會轉換成數據。這個新行被認爲是您的下一個電話nextLine()的輸入。你將需要把人工nextLine(),來電後nextInt()或直接使用nextLine()和分析輸入作爲int

count = sc.nextInt(); 
sc.nextLine(); 

count = Integer.parseInt(sc.nextLine()); 
相關問題