【问题标题】:Why is my first .nextline in the loop skipped then not skipped the next time around? and how do I stop it from overwriting? [duplicate]为什么我在循环中的第一个 .nextline 被跳过然后下一次没有被跳过?以及如何阻止它被覆盖? [复制]
【发布时间】:2012-01-24 13:12:36
【问题描述】:

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

【问题讨论】:

    标签: java loops text while-loop filewriter


    【解决方案1】:

    当您为nextInt() 输入int 时,您也按下回车键以接收输入,这意味着也读取了一个新行。此新行被视为您下次调用nextLine() 的输入。您需要在调用nextInt() 后添加人工nextLine() 或直接使用nextLine() 并将输入解析为int

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

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

    【讨论】:

      【解决方案2】:

      .nextInt() 没有抓住你的 Enter 压力。您需要在其后放置一个空白的 .nextLine()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-11
        • 1970-01-01
        • 2014-10-27
        • 1970-01-01
        • 2021-03-19
        • 2015-05-06
        • 2013-05-08
        • 1970-01-01
        相关资源
        最近更新 更多