2

I needed to create a basic program to input text to a .txt document so I created this but I don't see why the first question is skipped when the program is first run.

It doesn't happen if the first question that sets the loop isn't there. Also how do I stop it from overwriting what is already there in the txt document when all I want it to do is add to it.

So far the last method seems to work far but I thought I would still include it.

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());
    }
}
}
Vaandu
  • 4,857
  • 12
  • 49
  • 75

2 Answers2

1

When you are inputting the int for nextInt() you are also pressing enter for the input to be received, which translates into a new line being also read. This new line is considered input for your next call to nextLine(). You will need to put an artificial nextLine() after the call to nextInt() or use nextLine() directly and parse the input as an int:

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

or

count = Integer.parseInt(sc.nextLine());
Tudor
  • 61,523
  • 12
  • 102
  • 142
0

.nextInt() does not catch your Enter press. You'll need to put a blank .nextLine() after it.

Luminously
  • 299
  • 1
  • 6