简体   繁体   English

Java扫描仪输入循环

[英]Java Scanner Input Loop

I've got a loop that is controlled by a variable called running which tells if the program is running or not. 我有一个循环,该循环由一个名为running的变量控制,该变量告诉程序是否正在运行。 I am trying to achieve a loop that the user enters a command, and the program is answering him, but for some reason, It's seems like my String splits if its more than one word, this is what I have tried: 我正在尝试实现一个循环,用户输入命令,程序正在回答他,但是由于某种原因,如果我的String拆分了多个单词,这似乎是我尝试的方法:

import java.util.Scanner;
public class ScannerTest{
    private boolean running = true;
    public ScannerTest(){
        Scanner s = new Scanner(System.in);
        while(running){
           String command = s.next();
           System.out.println(command);
        }
    }
}

If I am entering two or more words in the Scanner, It seems to split them. 如果我在扫描仪中输入两个或多个单词,似乎会将它们分开。

Input  >> Hello what's your name?
Output >> Hello
       >> what's
       >> your
       >> name?

Maybe it's because of the While loop? 也许是因为While循环? How can i fix it? 我该如何解决? Thanks in advance. 提前致谢。

Scanner#next() does just this -- it grabs the next token defined by any white-space delimiter(s), and does not get the next line. Scanner#next()就是这样做的-它捕获由任何空格定界符定义的下一个标记,并且不获取下一行。 If your words have white space between them, it will grab the individual words one at a time with each invocation of the method. 如果您的单词之间有空格,那么每次调用该方法时,它都会一次抓住一个单词。

Use Scanner#nextLine() instead if you want to grab the complete line that the user entered. 如果要获取用户输入的完整行,请改用Scanner#nextLine()

Edit: this question has to be a duplicate of another somewhere on this site. 编辑:此问题必须与该网站上其他地方的重复。

next() method will split your input by space delimiter. next()方法将使用空格分隔符分割您的输入。

nextLine() method will fix your problem. nextLine()方法将解决您的问题。 nextLine(); nextLine(); will read the entire line at once. 将一次读取整行。

Replace String command = s.next(); 替换String command = s.next(); to String command = s.nextLine(); String command = s.nextLine();

You're using 您正在使用

System.out.println();

just use 只是使用

System.out.print();

only use println if you want the next output/input to be entered onto the next line. 仅在希望将下一个输出/输入输入到下一行时才使用println。

为什么不使用end-of-file indicator ,您在解决方案中使用的循环称为sentinel-controlled repetition ,我认为使用end-of-file indicator来控制它的更好的价值是看我的答案java Scanner.hasNext()的用法

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

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