0

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

}
Citation
  • 1
  • 1
  • 5

3 Answers3

0

A while loop with hasNext() will not break until you use an End Of File condition like shown below

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

As you are reading from stdin, it either expect an EOF character(Ctrl+D on Linux/Unix/Mac or Ctrl+Z on Windows) or a condition to break out of the loop.

Akhil
  • 368
  • 4
  • 16
  • I can't use this method as I have been given a specific input to use. The input does have a specification of 255 chars, how might I use that to stop the loop? – Citation Feb 22 '17 at 03:42
  • I have to copy and paste from a text file and use scanner – Citation Feb 22 '17 at 03:59
0

You can set while(true) for infinite loop and break it once it matches exit

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

For Line/word count, you can use

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());
    }
Atul
  • 1,536
  • 3
  • 21
  • 37
  • I can't use this method as I have been given a specific input to use. The input does have a specification of 255 chars, how might I use that to stop the loop? – Citation Feb 22 '17 at 03:42
  • Can't you break loop on the basis of Carriage Return or Line Feed? – Atul Feb 22 '17 at 03:44
0

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

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

synchronizer
  • 1,955
  • 1
  • 14
  • 37