Skip to content
Advertisement

Why is the following code showing twice the statements inside try block inside the loop?

Following is the program for reversing a word using a stack. There is no problem in implementation of stack. It is executing finely. When ctrl-c is pressed, it prints the content of try-catch block twice or even thrice. What causes this?

import java.util.NoSuchElementException;
import java.util.Scanner;
class WordReversal {
    public static void main(String args[]) {
    StackIFace sfWord;  // interface reference
    Stack s = new Stack();
    sfWord = s;
    Scanner sc = new Scanner(System.in);
    System.out.println("Control-C to stop.");
    for(;;) {
        String senWord = "", revWord = "";
        try {
                System.out.println("Enter a word: ");
                senWord = sc.next();
                for(int i=0;i<senWord.length();i++)
                sfWord.push(senWord.charAt(i));
                for(int i=0;i<senWord.length();i++)
                    revWord+=sfWord.pop();
                System.out.println("Original Word::"+senWord+"nReversed Word::"+revWord);
            } catch(NoSuchElementException NSEe) {
            System.out.println("Control-C command accepted.nQuitting...");
            //break;
            }
        }
    }
}

One thing to notice here is if I put break (just remove two forward slashes in above code), the problem is solved but exactly what is causing this? Is Scanner causing this or is it a language problem?

Advertisement

Answer

NoSuchElementException is not actually “intercepting ctrl/C”. So what’s likely happening is you’re terminating input, the next() call throws an exception because there is no input, you print a message, and loop round to do it again.

Input is still terminated, so the next() call throws an exception….

What surprises me is thus not that it loops, but that it stops looping after 2 or 3 times. Maybe some other exception gets thrown that you don’t catch; hard to say without adding a handler to check.

But the root issue is: if you want that particular exception to quit the program, you need to write code that quits the program. You in fact did that when you wrote the ‘break’ out of the loop.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement