while循环只执行一次 [英] While loop executes only once

查看:978
本文介绍了while循环只执行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难搞清楚为什么while循环不会实际循环。它运行一次并停止。

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!

推荐答案

问题是当你打电话给 nextDouble(),它会消耗数字,但不会消耗数字后面的换行符。要解决此问题,只需在调用 nextDouble()之后插入一行代码 inp.nextLine();

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

示例和完整说明:

假设输入km ,按enter键,123,按回车键。然后从程序的角度来看,输入流是km \\\
123 \ n

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

代码 String convert = inp.nextLine(); 获取值km并将输入推进到第一个\ n

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

代码 double num = inp.nextDouble( ); 获取字符串123并返回值(double)123.0。它在看到'\ 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.

在循环的下一次迭代中, inp.nextLine(); 看到\ n立即,所以 String convert =; 。这会触发循环中的 else 大小写,因此它会退出循环。

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.

这篇关于while循环只执行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆