0

im trying to sanitize the input given by a user by converting the input to lowercase and taking the first letter of the input in order to result in a "y" or "n". however, i keep getting an exception thrown

here is a snippit of my code

System.out.println("Welcome to \"My Pet Budget\" 1.2!");
    System.out.println("");
    System.out.println("Enter the month and year for your budget:");
    monthYear = keyboard.nextLine();
    System.out.println("Enter the name of your pet:");
    petName = keyboard.nextLine();
    System.out.println("Enter the type of your pet:");
    petType = keyboard.nextLine();
    System.out.println("Enter the breed of your pet:");
    petBreed = keyboard.nextLine();
    System.out.println("Enter the age of your pet:");
    petAge = keyboard.nextInt();

    // item if statements
    System.out.println("Would you like to add an item? (y/n):");
    String answer;
    answer= keyboard.nextLine(); // lower case and use the first letter to simplify
                                                                // edge cases.
    if (answer.toLowerCase().charAt(0)== 'y') {
        System.out.println("Enter the name for item 1:");
        itemName1 = keyboard.nextLine();
        System.out.println("Enter the price for item 1:");
        itemPrice1 = keyboard.nextDouble();
        System.out.println("Enter the quantity for item 1:");
        itemQuantity1 = keyboard.nextInt();

and it throws an out-of-bounds exception (probably having to do with the .charat method.

if anyone can help i will be very greatfull

  • `answer` is an empty string, because the `.nextLine()` comes after a `.nextInt()`. You can't get the first character of an empty string, hence the exception. – Ivar Feb 20 '21 at 01:29

0 Answers0