java - How to make a do statement restart? -


i not know how explain here go.

i testing bigger program have make. in program have validate input user see if being accepted valid answer.

i have code if input invalid if attempted enter letter code crashes error:

enter letter: f answer not valid. enter letter: exception in thread "main" java.lang.stringindexoutofboundsexception: string index out of range: 0     @ java.lang.string.charat(string.java:695)     @ example.main(example.java:18) 

here code:

import java.util.scanner;  public class example {     public static void main(string[] args)     {         scanner input = new scanner(system.in);           boolean userinput;                  {                 char user_answer = 0;                   system.out.println("enter letter:");                 user_answer=input.nextline().charat(0);                  if ( user_answer == 'a')                 {                      userinput = true;                 }                 else if (user_answer == 'b')                 {                      userinput = true;                 }                 else if (user_answer == 'c')                 {                      userinput = true;                 }                 else if (user_answer == 'd')                 {                      userinput = true;                 }                 else                 {                     system.out.println("your answer not valid.");                     userinput = false;                     input.next();                 }           }          while   (!userinput);       }  }        

either remove input.next() or change input.nextline() what's happening input.next() catch a input. go beginning of do , start over, , input.nextline() had pressed enter input a , a consumed input.next().


Comments