java - Errors using the try catch block -


i having problems when run code. executes first , second system.out.println fine. program calls iohelper , allows me input number. once enter value, prints "obtained: xxxx" , prints "please enter wind velocity:" followed list of errors.

exception in thread "main" java.util.nosuchelementexception     @ java.util.scanner.throwfor(unknown source)     @ java.util.scanner.next(unknown source)    @ java.util.scanner.nextdouble(unknown source)    @ assignment1_14.iohelper(assignment1_14.java:49)    @ assignment1_14.main(assignment1_14.java:27) 

i using eclipse.

public class assignment1_14 {  // declaring constants final static double gravity = 9.807; final static double mass_initial = 0.008; final static int launch_vel = 22; final static int density = 1900; final static double burn_rate = 0.003; final static int min_angle = -15; final static int max_angle = 15; final static int min_wind = -22; final static int max_wind = 22;  public static void main(string[] args){     system.out.println("hello, in order launch roman candle, please set \n"             + "the launch angle , wind velocity. note, launch angle must \n"             + "between 15 degrees , -15 degrees.\n\n");      system.out.println("please enter launch angle: ");     double angle = iohelper(min_angle, max_angle);     system.out.println("obtained: " + angle);      system.out.println("please enter wind velocity: "); 27  double windvel = iohelper(min_wind, max_wind);     system.out.println("obtained: " + windvel); } // end main method  public static double iohelper (double low, double high) {     scanner screen = new scanner(system.in);     double num = 0;     boolean inputok = false;     string dump = null;      while (!inputok) {         try {     49      num = screen.nextdouble();             dump = screen.nextline();              if (num < low || num > high) {                 inputok = false;                 continue;             } // end if statement             inputok = true;         } catch (inputmismatchexception e) {             dump = screen.nextline();             system.out.println("\"" + dump + "\" not legal double, "             + "please try again!");         } // end try-catch block     } // end input loop     screen.close();     return num; } // end iohelper method 

the nosuchelement exception gets thrown because there no element read. https://docs.oracle.com/javase/7/docs/api/java/util/scanner.html#next%28%29

either catch it, or add check input before read token

while (!inputok) {     try {         if(!screen.hasnext()) continue;         num = screen.nextdouble(); .... 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -