-1

This is a code snippet that shows me trying to write to a file.

public void printContents() {
  int i = 0;
  try {
    FileReader fl = new FileReader("Product List.txt");
    Scanner scn = new Scanner(fl);
    while (scn.hasNext()) {
      String productName = scn.next();
      double productPrice = scn.nextDouble();
      int productAmount = scn.nextInt();
      System.out.println(productName + " is " + productPrice + " pula. There are " + productAmount + " items left in stalk.");
      productList[i] = new ReadingAndWritting(productName, productPrice, productAmount);
      i = i + 1;
    }
    scn.close();
  } catch (IOException exc) {
    exc.printStackTrace();
  } catch (Exception exc) {
    exc.printStackTrace();
  }
}

public void writeContents() {
  try {
    //FileOutputStream formater = new FileOutputStream("Product List.txt",true);
    Formatter writer = new Formatter(new FileOutputStream("Product List.txt", false));
    for (int i = 0; i < 2; ++i) {
      writer.format(productList[i].name + "", (productList[i].price + 200.0 + ""), (productList[i].number - 1), "\n");
    }
    writer.close();
  } catch (Exception exc) {
    exc.printStackTrace();
  }
}

The exception thrown while trying to run this code is:

java.util.NoSuchElementException at ReadingAndWritting.printContents(ReadingAndWritting.java:37).

I tried multiple things and only ended up with: "cokefruitgushersAlnassma" in the file. What I want is:

coke 7.95 10
fruitgushers 98.00 6
Alnassma 9.80 7
Thabiso Motswagole
  • 146
  • 1
  • 2
  • 17

1 Answers1

1

The Problem seems to be in

     String productName = scn.next();

     // Here:
     double productPrice = scn.nextDouble();

     // And here:
     int productAmount = scn.nextInt();

After scn.next(), you don't check if scn.hasNext() before requesting the next element (double or int, respectively). So, either your file is not complete, or not in the exact structure you expect, or you just missed the two additional checks before trying to work with data which just isn't there.

Solution could be like:

   while (scn.hasNext()) {

     String productName = scn.next();

     if ( scn.hasNext() ) {

       double productPrice = scn.nextDouble();

       if ( scn.hasNext() ) {

         int productAmount = scn.nextInt();

         // Do something with the three values read...

       } else {
         // Premature end of file(?)
       }

     } else {
         // Premature end of file(?)
     }

   }
JimmyB
  • 12,101
  • 2
  • 28
  • 44