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

Time:11-16

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

CodePudding user response:

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.

  • Related