简体   繁体   中英

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

This is my code:

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);
            }
        }
    }
}

this code does well for single digit integer, but if the input is double-digit, then it messes.

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.

Just try to parse whole line that you get with readLine():

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

You will get exception if that string is not a number.

"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."

Based on this, it is really unclear what you're trying to accomplish. The exception you're getting is because of your if (i % 2) . When you input 1 3 66 58 7 , your code processes the 1 , skips the space, processes the 3 , skips the space, processes the 6 instead of 66 , skips the second 6 , then processes the space and that's when your exception occurs.

Your sample codes indicates that you are just trying to convert each string of numbers, separated by space, into an integer.

One approach to do that would be to use String.split() to split the input apart by the space and try to convert each piece.

Something like:

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]);
            }
        }
    }
}

Result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM