簡體   English   中英

如何在Java中使用BufferedReader接受整數(2位或更多位)輸入

[英]How to take integer(2 or more digit) inputs using BufferedReader in java

這是我的代碼:

import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
        String s = b.readLine();
        for (int i = 0; i < s.length(); i++)
        {
            if (i % 2 == 0) {
                int a = Integer.parseInt(String.valueOf(s.charAt(i)));
                System.out.print(a);
            }
        }
    }
}

這段代碼對於一位整數是很好的選擇,但是如果輸入是兩位數,那么它就會混亂。

我的輸入:1 3 6 5 7輸出:1 3 6 5 7運行良好,但是,如果輸入為:1 3 66 58 7輸出:發生異常。 如何處理這樣的兩位數整數輸入。

只需嘗試解析使用readLine()獲得的整行:

String s = b.readLine();
int a = Integer.parseInt(s);

如果該字符串不是數字,則會出現異常。

"my input: 1 3 6 5 7 output: 1 3 6 5 7 works well but, 
if the input is : 1 3 66 58 7 output: exception occurs. 
how to handle such double digit integer inputs."

基於此,目前還不清楚您要完成什么。 您得到的異常是由於if (i % 2) 當您輸入1 3 66 58 7 ,您的代碼將處理1 ,跳過空格,處理3 ,跳過空格,處理6而不是66 ,跳過第二個6 ,然后處理空格,這就是您的異常發生的時間。

您的示例代碼表明您只是在嘗試將每個數字字符串(用空格分隔)轉換為整數。

一種方法是使用String.split()將輸入按空格分開,然后嘗試轉換每一部分。

就像是:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class StackOverflow {
    public static void main(String[] args) throws Exception {
        BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
        String s = b.readLine();
        String[] pieces = s.split(" ");

        for (int i = 0; i < pieces.length; i++) {
            try {
                int a = Integer.parseInt(pieces[i]);
                System.out.print(a + " ");
            } catch (Exception e) {
                System.out.printf("%s is not an integer\r\n", pieces[i]);
            }
        }
    }
}

結果:

1 3 66 58 7 // Input
1 3 66 58 7 // Output

暫無
暫無

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

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