简体   繁体   English

While循环仅执行一次

[英]While loop executes only once

I have a hard time figuring out why the while loop won't actually loop. 我很难弄清楚为什么while循环实际上不会循环。 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. 问题在于,当您调用nextDouble() ,它将使用该数字,但不使用该数字之后的换行符。 To fix this, simply put a line of code inp.nextLine(); 要解决此问题,只需在inp.nextLine();放入一行代码inp.nextLine(); after calling nextDouble() . 在调用nextDouble()


Example and full explanation: 示例和完整说明:

Suppose your input "km", press enter, "123", press enter. 假设您输入“ km”,按回车,“ 123”,按回车。 Then from the program's point of view, the input stream is "km\\n123\\n" . 然后从程序的角度来看,输入流为"km\\n123\\n"

The code String convert = inp.nextLine(); 代码String convert = inp.nextLine(); gets the value "km" and also advances the input past the first "\\n" . 获得值"km" ,并且使输入超出第一个"\\n"

The code double num = inp.nextDouble(); 代码double num = inp.nextDouble(); gets the string "123" and returns the value (double)123.0 . 获取字符串"123"并返回值(double)123.0。 It stops parsing when it sees the '\\n' , but it does not consume the character - it remains in the input buffer. 看到'\\n'时,它将停止解析,但不占用字符-保留在输入缓冲区中。

In the next iteration of the loop, inp.nextLine(); 在循环的下一个迭代中, inp.nextLine(); sees "\\n" immediately, so the String convert = ""; 立即看到"\\n" ,因此String convert = ""; . This triggers the else case in your loop, so it exits the loop. 这会触发循环中的else情况,因此退出循环。

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. ...不是true ,请将boolean continue1设置为false ,这将在下一次迭代时中断循环。

Please also note that since it's a boolean, you can (and should) write your while statement as such: 另请注意,由于它是布尔值,因此您可以(并且应该)这样编写while语句:

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. 另请注意,在扫描特定类型(例如Scanner.nextDouble ,应尝试/捕获Exception ,因为如果输入为意外类型,这很可能会破坏带有堆栈跟踪的代码。

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. 在您的代码中,在while循环中初始化扫描器对象时仍然存在一个问题,它将解决打印两次行的问题。 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(). 由于System.out.println(),nextLine()正在读取空行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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