Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Out of bounds for charAt(0), any ideas?

Options
  • 11-11-2013 4:47pm
    #1
    Registered Users Posts: 8,671 ✭✭✭


    Hey, I'm new enough to java and just can't see what mistake I am making, it's probably something obvious and stupid, any reason why I'm getting out of bounds for charAt?


    import





    java.util.Scanner;





    public





    class NumberGuess {





    public static void main(String args [])


    {



    Scanner scan =
    new Scanner(System.in);



    System.
    out.println("Please enter the range");




    int range = scan.nextInt();



    String start =
    new String("No");



    System.
    out.println("Pick a number in your head. Are you ready to start?");




    while(start.charAt(0) != 'y' && start.charAt(0) != 'Y')


    {

    start = scan.nextLine();

    }


    long time = System.currentTimeMillis();



    System.
    out.println("For each guess please enter Higher, Lower or Correct");




    }

    }


    EDIT: That copy and paste went horribly, I'll try to sort it later.


Comments

  • Moderators, Society & Culture Moderators Posts: 17,642 Mod ✭✭✭✭Graham


    Use the Code tags around your code

    [HTML]
    your code goes here
    
    [/HTML]


  • Registered Users Posts: 1,311 ✭✭✭Procasinator


    When you use nextInt from Scanner, it will only read the number, leaving the newline caused by pressing Enter. So, nextInt is called, and you type say 10+Enter, which becomes "10\r\n". Scanner then takes 10, leaving "\r\n" (newline) in the scanner buffer. Your next call to nextLine() will then take everything from it's current position, until the newline. As the newline is the first character it sees, this ends up being an empty string. As it's an empty string, you get an out of bounds exception.

    Easiest fix is probably to use start.isEmpty() condition in your loop.
    while(start.isEmpty() || (start.charAt(0) != 'y' && start.charAt(0) != 'Y'))
    [...]
    


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,097 Mod ✭✭✭✭Tar.Aldarion


    The first time it comes to the while, start has a value, however you then change it to be an empty string with
    start = scan.nextLine();
    

    And as you do not check in your while for null or lengths of 0 there is an exception.
    basically you are setting your string to nothing.


Advertisement