Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I convert a BufferedReader-Input (String) to Integer and save it in an Integer List in java?

I would like to search for an Integer in a String given by a BufferedReader. The Integers have to be saved inside an Integer-List and be returned.
My Idea was splitting the String in a String [ ] and save the Integers with Integer.parseInt directly inside the Array-List, but unfortunatelly i only get NumberFormatExceptions, although the String [ ] is filled.
Could someone give me some advice?

    public List<Integer> getIntList(BufferedReader br) {
        List <Integer> List = new ArrayList<>();
        try{
            while(br.ready()){
                try{
                    String line = (br.readLine());
                    String [] arr = line.split("\\s");
                    for (String s : arr) {
                        System.out.println(s);
                    }
                    if(line.equals("end")){
                        return List;
                    }
                    for (String s : arr) {
                        List.add(Integer.parseInt(s));

                    }
                }
                catch(IOException e){
                    System.err.println("IOException");
                }
                catch(NumberFormatException e){
                    System.out.println("Number");
                }
            }
            return List;
        }
        catch(IOException e){
            System.err.println("IOException");
        }
    return null;
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You catch NumberFormatException in a wrong place so that you cannot continue number searching loop. You have to wrap this line List.add(Integer.parseInt(s)); into try catch block. Also never start variable name with capital letter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading