如何修复 数字格式异常 错误当我尝试将" 97"解析为 int 时使用整数变量时?



我正在解决这个比较问题,在超过时间限制时,我决定跟踪最大整数元素,而不是每次都搜索它。新代码在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()语句之一引起的。

最新更新