簡體   English   中英

在使用 BufferedReader 讀取同一行中的 2 個數字時,我遇到了錯誤:java.lang.NumberFormatException:對於輸入字符串:“2 3”

[英]while using BufferedReader to read 2 numbers in same line I was having an Error: java.lang.NumberFormatException: For input string: “2 3”

我是 BufferedReader 的新手。 我試圖在同一行中輸入 2 個數字,例如: 2 3 為此,我編寫了以下代碼。

import java.io.*;
public class Main
{
    public static void main(String[] args)throws IOException{
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(bufferedReader.readLine().trim());

        int M = Integer.parseInt(bufferedReader.readLine().trim());
        System.out.println("N="+N+"M="+M);
    }
}

所以我遇到了以下錯誤。

Exception in thread "main" java.lang.NumberFormatException: For input string: "2 3"                                                 
        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 Main.main(Main.java:15)                                                                                                  

代碼有什么問題。 提前致謝。

在同一行接受多個輸入時,您應該定義一個用於分隔輸入的字符。 在您的示例中,這似乎是通過空格完成的。

您需要使用split()從單行輸入創建一個響應數組作為字符串,然后使用Integer.parseInt()將它們分配給您需要的變量。

import java.io.*;
public class Main
{
    public static void main(String[] args) throws IOException {
        // Create BufferedReader and two ints
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        int N, M;

        // Take in inputs from user, and split them into an array using whitespace
        // '\\s+' matches at any whitespace size
        String[] inputs = bufferedReader.readLine().split("\\s+");

        N = Integer.parseInt(inputs[0]);
        M = Integer.parseInt(inputs[1]);

        System.out.println("N=" + N + " M=" + M);
    }
}

暫無
暫無

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

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