import java.util.*;import java.io.*;import java.lang.*;class Ex{ public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(newInputStreamReader(System.in)); int a,b,n,c; n=Integer.parseInt(br.readLine()); for(int i=1;i<=n;i++) { try { a=Integer.parseInt(br.readLine()); b=Integer.parseInt(br.readLine()); try { c=a/b; System.out.println(c); } catch (ArithmeticException e) { System.out.println(e); } } catch (InputMismatchException m) { System.out.println(m); } } }}上面提到的是我試圖運行的代碼,下面是 input_file.txt4 10310Hello10223.3230.0這是我得到的錯誤。Exception in thread "main" java.lang.NumberFormatException: For input string: "4 " at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at Ex.main(Ex.java:11)
2 回答

慕碼人8056858
TA貢獻1803條經驗 獲得超6個贊
java.lang.NumberFormatException: For input string: "4 "
正如您從字符串上方的錯誤消息中看到的那樣,您嘗試解析的數字在末尾有一個空格,這將導致解析失敗。
要擺脫前導和尾隨空格,您可以在字符串上使用trim()方法:
a=Integer.parseInt(br.readLine().trim());

陪伴而非守候
TA貢獻1757條經驗 獲得超8個贊
我想你已經輸入了帶空格的數字 4。請檢查您的輸入。
對于輸入字符串:“4”
為了避免它,您可以添加如下修剪功能
Integer.parseInt(br.readLine().trim());
添加回答
舉報
0/150
提交
取消