2012-01-24 6 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()はEnterキーを押さない。後ろに空の.nextLine()を置く必要があります。

1

nextInt()intを入力するときには、入力を受け取るためにenterも押します。これは、読み取られる新しい行に変換されます。この新しい行は、nextLine()への次の呼び出しの入力と見なされます。

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

または

count = Integer.parseInt(sc.nextLine()); 
:あなたは intとして入力を nextInt()に呼び出した後、人工 nextLine()を入れたり、直接 nextLine()を使用して解析する必要があります。
関連する問題