2

.txtドキュメントにテキストを入力するための基本的なプログラムを作成する必要があったので、これを作成しましたが、プログラムを最初に実行したときに最初の質問がスキップされる理由がわかりません。

ループを設定する最初の質問がない場合は発生しません。また、txtドキュメントに追加するだけで、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());
    }
}
}
4

2 に答える 2

1

intforを入力しているときはnextInt()、入力を受信するために Enter キーも押しているため、新しい行も読み取られます。この新しい行は、次の への呼び出しの入力と見なされますnextLine()nextLine()の呼び出しの後に人工を置くnextInt()か、直接使用nextLine()して、入力を次のように解析する必要がありintます。

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

また

count = Integer.parseInt(sc.nextLine());
于 2012-01-24T13:22:00.233 に答える
0

.nextInt() は、Enter キーを押してもキャッチされません。空白の .nextLine() をその後に置く必要があります。

于 2012-01-24T13:14:13.410 に答える