簡體   English   中英

為什么在我的代碼的第 7 行中出現錯誤 [線程“主”java.lang.NumberFormatException:對於輸入字符串:“3”] 中的異常?

[英]why am i getting an error [Exception in thread "main" java.lang.NumberFormatException: For input string: "3"] in line 7 of my code?

所以我正在解決競爭編程中的一個問題,我必須將這些數字作為輸入......

3 
40 40 100
45 45 90
180 1 1

這是我的代碼:

package CP;
import java.io.*;
import java.util.*;
class Test {
    public static void main(String[] args)throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int t=Integer.parseInt(br.readLine());
        while(t-->0){
            StringTokenizer s=new StringTokenizer(br.readLine());
            int a=Integer.parseInt(s.nextToken());
            int b=Integer.parseInt(s.nextToken());
            int c=Integer.parseInt(s.nextToken());
            if(a+b+c==180) System.out.println("YES");
            else System.out.println("NO");
        }
        br.close();
    }
}

所以當我逐行輸入時,這段代碼可以正常工作。 但是當我一次將所有行作為輸入時,它會顯示 [Exception in thread "main" java.lang.NumberFormatException: For input string: "3"] 在第 7 行。為什么會這樣?

輸入中的 3 后面有一個空格。 這會導致Integer.parseInt(String)失敗。 修剪輸入行應該足以解決您的問題。

int t = Integer.parseInt(br.readLine().trim());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM