vendredi 6 mars 2015

Can't receive user input within a switch statement



I am just starting to write a menu which requires a user to choose which operation they want to carry out (like pages etc.). Once they have chosen the operation they need to be able to input with the keyboard to complete the task.


The problem is that I am receiving a 'StringIndexOutOfBoundsException: String index out of range' message when the user tries to input. Here is the code:



int choice;
boolean finished= false;
while (!finished) {
System.out.println(currentUser.getFirstName() + ". Please choose: ");
System.out.println("'l'- To like a page, 'e' to exit");
choice = keyboard.nextLine().charAt(0);
switch (choice) {
case 'l':
PageList.displayAllPages();
System.out.println("Enter the page to add");
int pIndex = keyboard.nextInt();
currentUser.insertPage(PageList.findPage(pIndex).toString());
break;
case 'e':
finished = true;
currentUser.saveMyPages(userDir);
currentUser.saveMyFriends();
break;
default:
System.out.println("Invalid entry");
}//switch
}//while


Obviously the problem is:



int pIndex = keyboard.nextInt();
currentUser.insertPage(PageList.findPage(pIndex).toString());


How can I fix this? Do I need to put it in a try catch statement?




Aucun commentaire:

Enregistrer un commentaire