为什么会收到NumberFormatException?

问题描述 投票:0回答:1

我在CodeChef平台中提出了一个问题,并且代码在我的IDE中而不是在CodeChef平台中得到了很好的执行。

当我使用Scanner代替Buffered Reader时,情况相同,我得到NoSuchElementException。

Exception in thread "main" java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:542)
    at java.lang.Integer.parseInt(Integer.java:615)
    at Codechef.main(Main.java:13)

这里是问题的链接:https://www.codechef.com/problems/LAYERS

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
    public static void main (String[] args) throws java.lang.Exception
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());
        while (T>0)
        {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int N = Integer.parseInt(st.nextToken());
            int C = Integer.parseInt(st.nextToken());
            int L[] = new int [N];
            int B[] = new int [N];
            int c[] = new int [N];
            int maxL =0, maxB=0;
            for(int i = 0;i<N;i++)
            {
                st = new StringTokenizer(br.readLine());
                L[i] = Integer.parseInt(st.nextToken());
                B[i] = Integer.parseInt(st.nextToken());
                c[i] = Integer.parseInt(st.nextToken());
                if(maxL<L[i])
                    maxL = L[i];
                if(maxB<B[i])
                    maxB = B[i];
            }
            int Graph[][] = new int[maxL/2][maxB/2];
            for(int i=0;i<N;i++)
            {
                for(int j=0;j<L[i]/2;j++)
                {
                    for(int k=0;k<B[i]/2;k++)
                    {
                      Graph[j][k]= c[i];
                    }
                }
            }
            int result[] =new int [C];
            for(int i=0;i<maxL/2;i++)
            {
                for(int j=0;j<maxB/2;j++)
                {
                    if(Graph[i][j]>0)
                    {
                        result[Graph[i][j]-1]++;
                    }
                }
            }
            for(int i=0; i<C;i++)
            {
                System.out.print(result[i]*4+" ");
            }
            T--;
        }
    }
}

帮助我为什么会出现错误。

java bufferedreader numberformatexception parseint stringtokenizer
1个回答
0
投票

如果我可以算到第13行(在此处发布的代码中总是很不稳定),则您的异常来自此行:

int T = Integer.parseInt(br.readLine());

br.readLine()在没有更多输入时返回null。由于这是您首次调用readLine(),因此,您的输入为空。您的异常消息中的null表示已将null传递给parseInt(或字符串"null",但这不太可能)。

此错误解释也与NoSuchElementException中报告的Scanner一致。

提示:我知道您的变量来自使用大写字母TNCLB的问题语句。仍然在Java中,让Java命名约定胜出:对变量使用小写字母。所以tcapitalT。变量名T特别令人困惑,因为T在泛型中经常用作类型参数。

© www.soinside.com 2019 - 2024. All rights reserved.