Hi I am having some problem understanding the do-while loop in the following program, and I was hoping for some help:

import java.io.File;
import static java.lang.System.out;
import java.util.Scanner;

class DeleteEvidence {

   public static void main(String args[]) {
      File evidence = new File("c:\\cookedBooks.txt");
      Scanner keyboard = new Scanner(System.in);
      char reply;

      do {
         out.print("Delete evidence? (y/n) ");
         reply = 
            keyboard.findWithinHorizon(".",0).charAt(0);
      } while (reply != 'y' && reply != 'n');

      if (reply == 'y') {
         out.println("Okay, here goes...");
         evidence.delete();
         out.println("The evidence has been deleted.");
      } else {
         out.println("Sorry, buddy. Just asking.");
      }
   }
}

Basically I know how the do-while loop works, as in it executes one time and then checks the conditions. In here the condition is while (reply != 'y' && reply != 'n'); and this is throwing me a little: so we want the program to display this out.print("Delete evidence? (y/n) "); only when the answer is not 'y' and not 'n'? Am I understanding this correctly?
thanks

Recommended Answers

All 4 Replies

no. you'll show that line at least once (the first iteration)
I'm not sure why you're going for "findWithinHorizon", you could also have gone for next or nextLine, and just read the first char.

Thanks stultuske, it's not my code, it comes from a book I am reading http://users.drew.edu/bburd/JavaForDummies/ , so I am just trying to understand this : - ).
I think I now understand the loop, which will continue to loop if the anser isn't y or n but anything else
thanks

personally, I would advice against this book.
if you are just starting out with java, you shouldn't use an IDE (yet). first get familliar with coding in notepad, and compiling, packaging and running your applications through command prompt.

I've gone over the "contents" a bit ... Very little, and not the best choice.
I would rather recommend Deitel & Deitel's Java, how to program
or Ivor Horton's Beginning Java - Java 7 Edition

thanks, is there a guide somewhere on how to do that with the command prompt (I use linux)?
Also, the deitel and deitel book you recommended, is it easy to understand even for somebody who has never done any coding before?
thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.