Reading only the integers from a txt file and adding the value up for each found

前端 未结 5 1944
情书的邮戳
情书的邮戳 2021-01-07 07:54

I am trying to read a txt file that contains strings with integers. I would like to be able to get just the integers from this file and add the value each to create a total.

5条回答
  •  臣服心动
    2021-01-07 08:35

    your code doesn't really do what your comments claim it does maybe you want this?

        import java.util.regex.Pattern;
    
        public void goalCount(){
                    int goals=0;// i dont see where this is used
                    double total=0;
                 try{
                    Scanner scan = new Scanner(new File("validtest.txt.txt"));
                    while (scan.hasNext()) {
                        String temp=scan.next();
                         if (isInteger(temp)) {
                             total+=Integer.ParseInt(temp);
                            System.out.println("Found :" + temp);
                         }
                         else{
                        System.out.println("Not Found :" + temp);}
                      }
                      scan.close();
                   }
                catch(Exception e){
    
                }
                   System.out.println("Total Goals:"+total); 
                }
    
        }
        public boolean isInteger( String input ) {
            Pattern p=Pattern.compile("-?\\d+");
            return input.matches(p.pattern());}
        }
        }
    

提交回复
热议问题