Search code examples
javasplittrimnumberformatexceptionparseint

When i try to read input using 'split' and trim() throws - NumberFormatException


public class Solution {
    public static void main(String[] args) throws IOException,NumberFormatException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int[] first_line = new int[2];
        String line = br.readLine();
        String[] strs = line.trim().split("\\s+");

        for(int i=0;i<2;i++)
        { 
            first_line[i] = Integer.parseInt(strs[i]);
        }

        int num = first_line[0];
        int tc = first_line[1];
        int[] lane = new int[num];
        String sec_line = br.readLine();
        String[] strs_line = sec_line.trim().split("\\s+");

        for(int i=0;i<num;i++)
        {
            lane[i] = Integer.parseInt(strs_line[i]);
        }

        for(int i=0;i<tc;i++)
        {
            String io = br.readLine();
            String[] ee = io.trim().split("//s+"); 
            int entry = Integer.parseInt(ee[0]);;// This is where my program throws exception
            int exit = Integer.parseInt(ee[1]);
            findMin(lane,entry,exit);
        }
    }

    public static void findMin(int[] lane,int entry,int exit)
    {
        int min = entry;
        for(int i=entry+1;i<exit;i++)
        {
            if(lane[i] < min)
            {
                min = lane[i];
            }
        }
        System.out.println(min);
    }
}
  1. First line of input contains two integers 8 5 , where 8 is number of lines i.e. 0-7 and 5 is the number of test cases.
  2. next line of input is the width of the 8 lanes that is from 0 to 7 i.e. 2 3 1 2 3 2 3 3
  3. next line of inputs are

0 3

4 6

6 7

3 5

0 7

Each pair separated by space are the various entry and exit points in the lane but when i try to read this it throws an NumberFormatException


Solution

  • Change your regex from

    String[] ee = io.trim().split("//s+");

    to

    String[] ee = io.trim().split("\\s+");