1
import java.util.ArrayList;
import java.util.Scanner;

public class Driver {
    private static ArrayList dogList = new ArrayList();
    private static ArrayList monkeyList = new ArrayList();//list of current monkeys
    // Instance variables (if needed)
    public static char userSelection; //allows variable to be used in printAnimals method

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        initializeDogList();
        initializeMonkeyList();
        do {
            displayMenu();
            userSelection = scnr.next().charAt(0); //users menu selection input
            switch (userSelection) {
                case '1': //calls intakeNewDog method
                    intakeNewDog(scnr);
                    break;
                case '2': //calls intakeNewMonkey Method
                    intakeNewMonkey(scnr);
                    break;
                case '3': //calls reserveAnimal Method
                    reserveAnimal(scnr);
                    break;
                case '4': //calls printAnimals method to print dogList array
                    printAnimals();
                    break;
                case '5': //calls printAnimals method to print monkeyList array
                    printAnimals();
                    break;
                case '6': //calls printAnimals method and prints list of available animals
                    printAnimals();
                    break;
                case 'q': //
                    System.out.println("Thanks for using our system, goodbye!");
                    System.exit(0);
                default: //handles input validation
                    System.out.println("Invalid selection, please try again.");
                    break;
            }
        } while (userSelection != 'q'); //keeps loop until user selection is 'q'
    }

    // This method prints the menu options
    public static void displayMenu() {
        System.out.println("\n\n");
        System.out.println("\t\t\t\tRescue Animal System Menu");
        System.out.println("[1] Intake a new dog");
        System.out.println("[2] Intake a new monkey");
        System.out.println("[3] Reserve an animal");
        System.out.println("[4] Print a list of all dogs");
        System.out.println("[5] Print a list of all monkeys");
        System.out.println("[6] Print a list of all animals that are not reserved");
        System.out.println("[q] Quit application");
        System.out.println();
        System.out.println("Enter a menu selection");
    }

    // Adds dogs to a list for testing
    public static void initializeDogList() {
        Dog dog1 = new Dog("Spot", "German Shepherd", "male", "1", "25.6", "05-12-2019", "United States", "intake", false, "United States");
        Dog dog2 = new Dog("Rex", "Great Dane", "male", "3", "35.2", "02-03-2020", "United States", "Phase I", true, "United States");
        Dog dog3 = new Dog("Bella", "Chihuahua", "female", "4", "25.6", "12-12-2019", "Canada", "in service", true, "Canada");
        dogList.add(dog1);
        dogList.add(dog2);
        dogList.add(dog3);
    }

    // Adds monkeys to a list for testing
    public static void initializeMonkeyList() { 
        Monkey monkey1 = new Monkey("George", "Squirrel Monkey", "male", "3", "2.1", "05-12-2019", "United States", "in service", false, "United States", "15.2", "11.3", "12.4" );
        Monkey monkey2 = new Monkey("Kong", "Marmoset", "male", "1", "1.89", "02-03-2020", "United States", "Phase I", false, "United States", "8.7", "6.8", "7.4");
        Monkey monkey3 = new Monkey("Matilda", "Capuchin", "female", "4", "6.54", "12-12-2019", "Canada", "in service", false, "Canada", "17.6", "16.29", "14.3");
        monkeyList.add(monkey1);  //adds monkey1, monkey2, monkey3 to monkeyList with their attributes
        monkeyList.add(monkey2);
        monkeyList.add(monkey3);
    }

    //intakeNewDog method
    public static void intakeNewDog(Scanner scanner) {
        String name;
        System.out.println("What is the dog's name?");
        name = scanner.nextLine();
        for(Dog dog: dogList) { //loop to validate if name does not already exist in dogList
            if(dog.getName().equalsIgnoreCase(name)) {
                System.out.println("\n\nThis dog is already in our system\n\n");
                return; //returns to menu
            }
        }
        scanner.nextLine();
        //Asks user for dogs info
        System.out.println("What is the dogs's breed?");
        String breed = scanner.nextLine();
        System.out.println("What is the dogs's gender?");
        String gender = scanner.nextLine();
        System.out.println("What is the dogs's age?");
        String age = scanner.nextLine();
        System.out.println("What is the dogs's weight?");
        String weight = scanner.nextLine();
        System.out.println("What is the dogs's aquisition date? Use the following format: __-__-__");
        String aquisitionDate = scanner.nextLine();
        System.out.println("What is the dogs's aquisition country?");
        String aquisitionCountry = scanner.nextLine();
        System.out.println("What is the dogs's trainging status? New dogs will always be 'Intake'.");
        String trainingStatus = scanner.nextLine();
        System.out.println("Is this dog reserved? Enter True for yes or False for no:");
        boolean reserved = scanner.nextBoolean();
        System.out.println("Which country will this dog be in service?");
        String inServiceCountry = scanner.nextLine();
        // Creates instantiated object and adds to dogList
        Dog new_Dog = new Dog(name,
                              breed,
                              gender,
                              age,
                              weight,
                              aquisitionDate,
                              aquisitionCountry,
                              trainingStatus,
                              reserved,
                              inServiceCountry);
        dogList.add(new_Dog);
        System.out.println("This dog has been added to the system."); //confirmation and return to menu
        return;
    }

    public static void intakeNewMonkey(Scanner scanner) {
        //array list of allowed monkeys to validate user input for species
        ArrayList<String> allowedMonkeysList = new ArrayList<String>();
        allowedMonkeysList.add("Capuchin");
        allowedMonkeysList.add("Guenon");
        allowedMonkeysList.add("Macaque");
        allowedMonkeysList.add("Marmoset");
        allowedMonkeysList.add("Squirrel Monkey");
        allowedMonkeysList.add("Tamarin");

        //loop to validate if monkeys name already exist within monkeyList          
        System.out.println("What is the monkey's name?");
        String name = scanner.nextLine();
        for(Monkey monkey: monkeyList) {
            if(monkey.getName().equalsIgnoreCase(name)) {
                System.out.println("\n\nThis monkey is already in our system\n\n");
                return;
            }
        }
        scanner.nextLine();  //allows user to input string name
        System.out.println("What is the monkey's species?"); 
        String species = scanner.nextLine();
        if (allowedMonkeysList.contains(species)!= true) {
            System.out.println("This species of monkey is not eligible to be an rescue animal.");
            return;
        } 
        //Asks user for monkey's info
        System.out.println("What is the monkey's gender?");
        String gender = scanner.nextLine();
        System.out.println("What is the monkey's age?");
        String age = scanner.nextLine();
        System.out.println("What is the monkey's weight?");
        String weight = scanner.nextLine();
        System.out.println("What is the monkey's aquisition date?");
        String aquisitionDate = scanner.nextLine();
        System.out.println("What is the monkey's aquisition country?");
        String aquisitionCountry = scanner.nextLine();
        System.out.println("What is the monkey's trainging status?  New monkeys will always be 'Intake'.");
        String trainingStatus = scanner.nextLine();
        System.out.println("Is this monkey reserved?  Enter true for yes or false for no: ");
        boolean reserved = scanner.nextBoolean();
        System.out.println("Which country will this monkey be in service?");
        String inServiceCountry = scanner.nextLine();
        System.out.println("Since this is a monkey, we'll need additional information."); //Monkey needs additional info not used by dog
        System.out.println("What is the monkey's tail length?");
        String tailLength = scanner.nextLine();
        System.out.println("What is the monkey's height?");
        String height = scanner.nextLine();
        System.out.println("What is the monkey's dody height?");
        String bodyLength = scanner.nextLine();
        //instantiates new_monkey object and adds to monkeyList array list
        Monkey new_Monkey = new Monkey(name,
                                       species,
                                       gender,
                                       age,
                                       weight,
                                       aquisitionDate,
                                       aquisitionCountry,
                                       trainingStatus,
                                       reserved,
                                       inServiceCountry,
                                       tailLength,
                                       height,
                                       bodyLength);
        monkeyList.add(new_Monkey);
        System.out.println("This monkey has been added to the system.");            
    }
}

The input validation for both intakeNewDog and intakeNewMonkey methods won't execute correctly and return to menu if there is a match between the user's input and the ArrayList. It just continues onto the rest of the of the code and executes the remainder print statements regardless of if the name matches or not. I've tried removing the enhanced for loop and using a .contains() method to verify the input with no luck. We haven't gone over using list stream so I have no idea how to approach this from that angle.

Abra
  • 19,142
  • 7
  • 29
  • 41
William
  • 21
  • 1
  • I think the problem is in the first scanner reading. Use `userSelection = scnr.nextLine().charAt(0);` instead of `userSelection = scnr.next().charAt(0);`. – kiuby_88 Aug 12 '22 at 23:40
  • Thank you, that worked. Though I'm not sure exactly why would've stopped the validation since the user is only being asked to input one word or character for the menu. Can you explain it for me? – William Aug 13 '22 at 00:55
  • 1
    Refer to [Scanner is skipping nextLine() after using next() or nextFoo()](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) There are **many** similar questions on SO. By the way, you are supposed to [search](https://stackoverflow.com/search) before asking (as is written in [ask]). Did you search for **[java] scanner next** ? Alternatively, in order to debug your code, you could add `System.out.println(userSelection);` before the `switch` statement in method `main`. – Abra Aug 13 '22 at 06:41

1 Answers1

0

That's how Scanner works.

The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token.

Whereas nextLine() advances past the end of line and returns the skipped characters.

Let's assume the user enters one word and hits Enter afterwards. If you call next(), Scanner will return the next token (the word the user entered) but will not remove the end of line character from the input. A subsequent nextLine() will read the rest of the current line, which is the empty string.

In this case you can simply use nextLine() instead of next() as User @kiuby_88 pointed out, already. In general, e.g. if you use one of the other nextXXX() methods, you might want to discard the remaining input on the current line by calling nextLine() afterwards before you read the 'real' next line.

Mihe
  • 2,270
  • 2
  • 4
  • 14