While loop executes only once

孤人 提交于 2019-12-02 10:36:10

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 Exceptions when you scan for specific types, e.g. Scanner.nextDouble, as this might very well break your code with a stack trace if the input is of an unexpected type.

mmratxs

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().

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!