当我尝试使用'split'和trim()抛出读取输入时 - NumberFormatException

时间:2014-09-21 05:42:45

标签: java split trim numberformatexception parseint

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. 第一行输入包含两个整数8 5,其中8是行数,即0-7,5是测试用例的数量。
  2. 下一行输入是8个通道的宽度,从0到7,即2 3 1 2 3 2 3 3
  3. 下一行输入
  4.   

    0 3

         

    4 6

         

    6 7

         

    3 5

         

    0 7

    每对以空格分隔的是通道中的各个入口和出口点,但是当我尝试读取它时会抛出NumberFormatException

2 个答案:

答案 0 :(得分:2)

更改正则表达式

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

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

答案 1 :(得分:1)

对于给定输入,ee [0]包含“0 3”且ee [1]为空。 “0 3”是异常的原因,因为它无法解析为int。

使用空格分隔数字而不是“// s +”。

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