I'm trying to use a do while loop to find out whether the user wants to check a dog or a cat into a kennel system in Java. The idea is that they enter either "dog" or "cat" when prompted, and any of entry will result in an error and they will be prompted again to enter the file name.
If "cat" or "dog" has been entered then the equivalent file will be assigned to the program (dogs.txt or cats.txt) and then the system will run and load that data into the program.
Here are the current variables:
private String filename; // holds the name of the file
private Kennel kennel; // holds the kennel
private Scanner scan; // so we can read from keyboard
private String tempFileName;
private String dogsFile = "dogs.txt";
private String catsFile = "cats.txt";
and the method that is causing an issue:
private KennelDemo() {
scan = new Scanner(System.in);
boolean fileNotCorrect = false;
System.out.print("Which animal are you looking to check into the kennel?: " + "\n");
System.out.println("Dog");
System.out.println("Cat");
tempFileName = scan.next();
do {
tempFileName.equals("dog");
filename = dogsFile;
fileNotCorrect = true;
/*tempFileName.equals("cat");
filename = catsFile;
fileNotCorrect = true;*/
}
while(fileNotCorrect = false);
System.out.println("That is not a valid filename, please enter either 'dog' or 'cat' in lowercase.");
And here's what's printed when you run the code:
**********HELLO***********
Which animal are you looking to check into the kennel?:
Dog
Cat
cat
That is not a valid filename, please enter either 'dog' or 'cat' in lowercase.
Using file dogs.txt
It's assigning a file to the program regardless of what's entered and then continues to load the program.
I've tried using catch { but it's not working for some reason, can anybody offer any help?
Thanks!
That's not how do-while is working. You are not even checking.
Use this:
do {
System.out.print("Which animal are you looking to check into the kennel?: " + "\n");
System.out.println("Dog");
System.out.println("Cat");
tempFileName = scan.next();
if(tempFileName.equals("dog") || tempFileName.equals("cat"))
{
filename = tempFileName.equals("dog") ? dogsFile : catsFile;
fileNotCorrect = true;
}else{
System.out.println("That is not a valid filename, please enter either 'dog' or 'cat' in lowercase.");
}
}
while(!fileNotCorrect);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With