如何按Enter退出while循环? [英] How do I exit a while loop by pressing enter?

查看:301
本文介绍了如何按Enter退出while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过按键盘上的 Enter 键来使while循环中断.我的代码是:

I am trying to get a while loop to break by pressing the Enter key on a keyboard. My code is:

package javaapplication4;
import java.util.ArrayList;
import java.util.Scanner;

public class JavaApplication4 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        ArrayList<Double> numbers = new ArrayList( );
        while (true) {
            System.out.println("Please enter the numbers seperated by a space: ");
            numbers.add(keyboard.nextDouble());
           //want the while loop to break here by pressing "enter" after entering array values
        }
        System.out.println(numbers);
    }

推荐答案

不要使用循环获取输入,即nextDouble.您真正想要的是一行输入,然后将其拆分为一个双精度列表.因此,请使用nextLine进行拆分,然后解析每个项目.像这样:

Don't use a loop for getting the input, or nextDouble. What you really want is one line of input, which you then split into a list of doubles. So use nextLine, split it, and parse each item. Something like this:

Scanner keyboard = new Scanner(System.in);
ArrayList<Double> numbers = new ArrayList( );
String input = keyboard.nextLine();
for(String item : input.split(" ")){
    numbers.add(Double.parseDouble(item));
}

这会忽略任何形式的输入验证,但它显示了一种通用方法.

This ignores any sort of input validation, but it shows a general approach.

之所以起作用,是因为一旦您单击"enter"(输入),它将结束第一行,这意味着扫描程序可以越过nextLine进入大部分代码.由于您再也不会尝试阅读任何内容,因此它不会阻止您等待任何更多输入,并且一旦完成就可以成功退出.

This will work because once you hit "enter", it ends the first line, meaning the scanner can move past the nextLine into the bulk of your code. Since you never try to read anything more, it doesn't block waiting for any more input, and can successfully exit once done.

这篇关于如何按Enter退出while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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