突破扫描仪hasNext()循环 [英] Breaking out of scanner hasNext() loop

查看:50
本文介绍了突破扫描仪hasNext()循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用扫描仪来处理用户输入的句子,如果出现单词嘿",它将添加到扫描仪中.所以基本上是字数统计.如何在不使用

I'm using scanner to process through a user input sentence and if the word "hey" appears it adds to scanner. So basically a word count. How do I break out of the infinite while(scan.hasNext()) loop without using something like

if(scan.next().equals("exit")

    break;

我无法以这种方式打破循环,因为我得到了无法更改的输入.

I can't break out the loop that way because I've been given inputs that I can't change.

 public static void main(String args[]) {
 Scanner scan = new Scanner(System.in);

 String speedLimit;
 int c = 0;
 while(scan.hasNext()){
    if (scan.next().equals("hey")){    
         c++;
    }
 }

 System.out.println(c);

}

推荐答案

如果您需要做的就是将一行文本作为字符串文字复制并粘贴到您的程序中

If all you need to do is copy and paste a line of text into your program as a string literal...

String msg = "hey you";
Scanner tokenizer = new Scanner(msg);
int count = 0;
while (tokenizer.hasNext()) {
    if (tokenizer.next().equals("hey")) {
        ++c;
    }
}

您可以使用Scanner标记字符串.您的循环应该结束.

You can use Scanner to tokenize a String. Your loop should end.

这篇关于突破扫描仪hasNext()循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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