2

我需要创建一个基本程序来将文本输入到 .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()您也按下回车键以接收输入,这将转换为也被读取的新行。此新行被视为您下次调用的输入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 回答