为什么跳过循环中的第一个.nextline然后下次不跳过?以及如何阻止它覆盖?

时间:2012-01-24 13:12:37

标签: java loops text while-loop filewriter

我需要创建一个基本程序来将文本输入到.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());
    }
}
}

2 个答案:

答案 0 :(得分:1)

当您为int输入nextInt()时,您还要按Enter键以接收要输入的内容,这将转换为也会读取的新行。这条新行被视为您下次拨打nextLine()的输入。您需要在调用nextLine()之后设置一个人为nextInt()或直接使用nextLine()并将输入解析为int

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

count = Integer.parseInt(sc.nextLine());

答案 1 :(得分:0)

.nextInt()没有捕获您的Enter按。你需要在它之后放一个空白的.nextLine()。