简体   繁体   中英

While loop executes only once

I have a hard time figuring out why the while loop won't actually loop. It runs through once and 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 you like to convert m-km or km-m(km for m-km and m for km-m)");

            String convert = inp.nextLine();
            if (convert.equalsIgnoreCase("km")) {
                System.out.println("Enter the mileage to be 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 the km to be converted.");
                double num = inp.nextDouble();
                double con = num * 0.621371;
                System.out.println(con);
                continue1 = true;
            } else {
                continue1 = false;
            }

        }
    }
}

I am trying to make it loop so the user would be able to convert units more than once. Any and all help is welcome!

The problem is that when you call nextDouble() , it consumes the number but not the newline that comes after the number. To fix this, simply put a line of code inp.nextLine(); after calling nextDouble() .


Example and full explanation:

Suppose your input "km", press enter, "123", press enter. Then from the program's point of view, the input stream is "km\\n123\\n" .

The code String convert = inp.nextLine(); gets the value "km" and also advances the input past the first "\\n" .

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

In the next iteration of the loop, inp.nextLine(); sees "\\n" immediately, so the String convert = ""; . This triggers the else case in your loop, so it exits the loop.

If either of the two conditions:

(convert.equalsIgnoreCase("km"))

or

(convert.equalsIgnoreCase("m"))

... is not true , you set your boolean continue1 to false , which will break your loop at the next iteration.

Please also note that since it's a boolean, you can (and should) write your while statement as such:

while (continue1) {
  // etc.
}

Note also that you should try/catch for Exception s when you scan for specific types, eg Scanner.nextDouble , as this might very well break your code with a stack trace if the input is of an unexpected type.

There is still one problem in your code intialize your scanner object in your while loop, it will resolve your problem of printing the line 2 times. Use This

import java.util.*;

public class mileskm {
public static void main(String[] args) {

    Scanner inp;
    boolean continue1 = true;

    while (continue1) {

        System.out.println("Would you like to convert m-km or km-m(km for m-km and m for km-m)");
       inp = new Scanner(System.in);

        String convert = inp.nextLine();
        if (convert.equalsIgnoreCase("km")) {
            System.out.println("Enter the mileage to be 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 the km to be converted.");
            double num = inp.nextDouble();
            double con = num * 0.621371;
            System.out.println(con);
            continue1 = true;
        } else {
            break;
        }

    }
}
}

Kindly Check It This Is the answer of your question written in comments

use

String convert = inp.next();

instead of

String convert = inp.nextLine();

nextLine() is reading empty line because of System.out.println().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM