java - While loop executes only once -


i have hard time figuring out why while loop won't loop. runs through once , stops.

import java.util.*;  public class mileskm {     public static void main(string[] args) {          scanner inp = new scanner(system.in);         boolean continue1 = true;          while (continue1 == true) {              system.out.println("would convert m-km or km-m(km m-km , m km-m)");              string convert = inp.nextline();             if (convert.equalsignorecase("km")) {                 system.out.println("enter mileage converted.");                 double num = inp.nextdouble();                 double con = num * 1.60934;                 system.out.println(con);                 continue1 = true;             } else if (convert.equalsignorecase("m")) {                 system.out.println("enter km converted.");                 double num = inp.nextdouble();                 double con = num * 0.621371;                 system.out.println(con);                 continue1 = true;             } else {                 continue1 = false;             }          }     } } 

i trying make loop user able convert units more once. , welcome!

the problem when call nextdouble(), consumes number not newline comes after number. fix this, put line of code inp.nextline(); after calling nextdouble().


example , full explanation:

suppose input "km", press enter, "123", press enter. program's point of view, input stream "km\n123\n".

the code string convert = inp.nextline(); gets value "km" , advances input past first "\n".

the code double num = inp.nextdouble(); gets string "123" , returns value (double)123.0 . stops parsing when sees '\n', not consume character - remains in input buffer.

in next iteration of loop, inp.nextline(); sees "\n" immediately, string convert = "";. triggers else case in loop, exits loop.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -