PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

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

 July 20, 2022     bufferedreader, integer, java, list, string     No comments   

Issue

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

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.



Answered By - Dmitry Pukhov
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing