Search code examples
javastringruntime-errorindexoutofboundsexception

How can i read inside loop in java without runtime error?


I am new in java and try to solve some problem(for practice) with it but I am getting runtime error and can't to know why or what I should search to know why that does.

This is my code.

Runtime error occur when I paste the test into the console but when I write it the runtime doesn't occur

And this is the link of the problem if that can help you to understand my error

https://codeforces.com/contest/1374/problem/C

    import java.util.*;
 
 
public class Main {
 
    public static void main(String[] args){
        Scanner reader = new Scanner(System.in);
        int t = reader.nextInt();
        ArrayList<Integer> anss = new ArrayList<>();
        for(int tst = 0; tst < t; tst++){
            int n = new Scanner(System.in).nextInt();
            String s = new Scanner(System.in).nextLine();
            int ans = 0;
            int open = 0;
            for(int i = 0; i < n; i++){
                if(s.charAt(i) == ')'){
                    if(open == 0) ans++;
                    else open--;
                } else {
                    open++;
                }
            }
            anss.add(ans);
        }
        for(int i : anss) System.out.println(i);
    }
}

Solution

  • To read that text, as provided by the Codeforces problem, you'll need to do two things:

    • Re-use the existing Scanner you've created (instead of creating a new one for each subsequent read)
    • Use Scanner.next instead of Scanner.nextLine

    To the first point, when a Scanner starts to parse the InputStream (when calling nextInt for example), it will consume a fair chunk of the stream. In this case, it consumes the entire stream, and so creating another Scanner operating on the same InputStream will fail when the stream is read.

    To the second, although the documentation for nextLine seems to indicate that the whole line will be returned:

    Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

    it actually seems to ignore the first token, ie the first non-whitespace part of the line. In this case, each line has no whitespace, so next will return the string you need. In the general case, it looks like getting the entire line revolves around doing something like:

    String s = reader.next() + reader.nextLine();