NoSuchElementException at java.util.Scanner.nextLine

45 Views Asked by At

My program encountered a runtime exception while attempting to read a file using a Scanner.

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1540)
    at Solution.main(Solution.java:11)

Input Format

The first line of input contains an integer , denoting the number of test cases. The next lines contain a string of any printable characters representing the pattern of a regex.

My code:

import java.util.Scanner;
import java.util.regex.*;
import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int testCases = Integer.parseInt(in.nextLine());
        while (testCases > 0) {
            String pattern = in.nextLine();
            char[] p = pattern.toCharArray();
            Stack<Character> stack = new Stack<>();
            for (int i = 0; i < p.length; i++) {
                if (p[i] == '(' || p[i] == '[' || p[i] == '{') {
                    stack.push(p[i]);
                } else if (p[i] == ')' || p[i] == ']' || p[i] == '}') {
                    if (!stack.isEmpty() && stack.peek() == '{' && p[i] == '}') {
                        stack.pop();
                    } else if (!stack.isEmpty() && stack.peek() == '[' && p[i] == ']') {
                        stack.pop();
                    } else if (!stack.isEmpty() && stack.peek() == '(' && p[i] == ')') {
                        stack.pop();
                    }
                }
            }
        }
    }
}
0

There are 0 best solutions below