【问题标题】:When i try to read input using 'split' and trim() throws - NumberFormatException当我尝试使用“split”读取输入时,trim() 会抛出 - NumberFormatException
【发布时间】:2014-11-15 08:43:27
【问题描述】:
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. 下一行输入是从 0 到 7 的 8 个通道的宽度,即 2 3 1 2 3 2 3 3
  3. 下一行输入是

0 3

4 6

6 7

3 5

0 7

以空格分隔的每一对都是车道中的各个入口和出口点,但是当我尝试阅读此内容时,它会抛出 NumberFormatException

【问题讨论】:

  • 您确定数组中的条目不是空字符串吗?
  • 您是否尝试在将字符串解析为int 之前打印它?这将帮助您解决问题。
  • //s+ 和 \\s+ 不是一回事。
  • @Mureinik 我正在运行一个自动化测试用例,我确定它不是空字符串
  • @NPE 现在我明白了,谢谢!!我太傻了,这是一个错字!

标签: java split trim numberformatexception parseint


【解决方案1】:

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

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

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

【讨论】:

  • 如果操作正确,\\s+ 是与空白相同 - 它只是覆盖的不仅仅是空格。
【解决方案2】:

从

更改您的正则表达式

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

到

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 2018-10-30
    • 2022-01-15
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多