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

查看:63
本文介绍了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",按回车,123",按回车.那么从程序的角度来看,输入流是"km 123 ".

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

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

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

代码 double num = inp.nextDouble(); 获取字符串 "123" 并返回值 (double)123.0 .当它看到 ' ' 时它会停止解析,但它不会消耗该字符 - 它保留在输入缓冲区中.

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

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

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

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

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