【问题标题】:Breaking out of scanner hasNext() loop打破扫描仪 hasNext() 循环
【发布时间】:2017-02-22 12:05:51
【问题描述】:

我正在使用扫描仪来处理用户输入的句子,如果出现“嘿”这个词,它就会添加到扫描仪中。所以基本上是字数。如何在不使用类似

的情况下跳出无限 while(scan.hasNext()) 循环
if(scan.next().equals("exit")

    break;

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

 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);

}

【问题讨论】:

  • while(scan.hasNext()) 不是无限循环。它会在到达输入结束时停止。
  • 使用scan.next() 会消耗一个令牌。
  • 具有下一个循环最终永远等待输入。
  • @synchronizer 还有其他方法可以从系统输入中搜索和统计单词吗?

标签: java loops


【解决方案1】:

在您使用 End Of File 条件之前,使用 hasNext() 的 while 循环不会中断,如下所示

while(scan.hasNext()){
  if(scan.next().equals("hey")){
     c++;
  }
  else if(scan.next().equals("exit")){
  break;
}

当您从标准输入读取数据时,它要么期望一个 EOF 字符(Linux/Unix/Mac 上的 Ctrl+D 或 Windows 上的 Ctrl+Z),要么是一个跳出循环的条件。

【讨论】:

  • 我无法使用此方法,因为我已经获得了要使用的特定输入。输入确实有 255 个字符的规范,我如何使用它来停止循环?
  • 我必须从文本文件中复制和粘贴并使用扫描仪
【解决方案2】:

你可以设置while(true)为无限循环,一旦匹配就中断它exit

    Scanner scan = new Scanner(System.in);
    int c = 0;
    while(true){
        if (scan.next().equals("exit"))
        {
            break;
        }
        else 
        {    
            c++;
        }
    }
    System.out.println(c);

对于行数/字数,您可以使用

String text=null;
    while(true)
    {
    Scanner inputText = new Scanner(System.in);
    int lineCount=0;
    text= inputText.nextLine();
    if(text!=null)
    {
        lineCount++;
    }
    StringBuilder sb = new StringBuilder();
    sb.append(text);   

    int wordcount=sb.length();

    System.out.println("Text : "+text);
    System.out.println("Number of Words:"+wordcount);
    System.out.println("Number of Lines: "+lineCount);
    System.out.println("Text afer removing  white spaces :"+text.replaceAll(" ", "").length());
    }

【讨论】:

  • 我不能使用这种方法,因为我已经获得了一个要使用的特定输入。输入确实有 255 个字符的规范,我如何使用它来停止循环?
  • 你不能在回车或换行的基础上打破循环吗?
【解决方案3】:

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

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

您可以使用 Scanner 对字符串进行标记。您的循环应该结束。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 2012-09-27
    • 2016-01-26
    相关资源
    最近更新 更多