当我尝试将“97”解析为 int 时使用 Integer 变量时如何修复 NumberFormatException 错误?

问题描述

我是 solving this comps question,超过时间限制后,我决定跟踪最大整数元素,而不是每次都搜索它。新代码在 case 1 下面的行抛出异常。 maiks 指的是堆栈内的最大值。

代码

public static void main(String[] args) throws IOException {
    BufferedReader br=new BufferedReader(new InputStreamReader(system.in));
    int n =Integer.parseInt(br.readLine());
    Stack<Integer> stk=new Stack<Integer>();
    char a;
    int input;
    for(int i=0;i<n;i++){
        a=(char)br.read();
        switch(a){
            case '1':
                br.skip(1);
                input=Integer.parseInt(br.readLine());
                stk.add(input);
                break;
            case '2':
                stk.pop();
                br.readLine();
                break;
            case '3':
                System.out.println(Collections.max(stk));
                br.readLine();
        }
    }
}

代码

public static void main(String[] args) throws IOException {
    BufferedReader br=new BufferedReader(new InputStreamReader(system.in));
    int n =Integer.parseInt(br.readLine());
    Stack<Integer> stk=new Stack<Integer>();
    char a;
    Integer maiks=0;
    int input=0;
    for(int i=0;i<n;i++){
        a=(char)br.read();
        switch(a){
            case '1':
                input=Integer.parseInt(br.readLine());
                stk.add(input);
                if(input>maiks){
                    maiks=input;
                }
                break;
            case '2':
                Integer p=stk.pop();
                if(p==maiks){
                    maiks=Collections.max(stk);
                }
                br.readLine();
                break;
            case '3':
                System.out.println(maiks);
                br.readLine();
        }
    }
}

代码抛出的异常

Exception in thread "main" java.lang.NumberFormatException: For input string: " 97"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at Solution.main(Solution.java:17)

解决方法

您正在尝试解析一个不是数字的字符串 - 在您的情况下它是“97”。前置空间导致了问题。您在修复它后得到的 NoSuchElementException 是另一个问题,并且可能是由您的 readLine() 语句之一引起的。