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

前端 未结 5 1945
情书的邮戳
情书的邮戳 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:36

    Edit:
    You'll have to excuse me, that method will not work. What you need to do is read one line at a time, then split the line by each space, to get an array of words. From there you can identify integers and store the value.

    final static String filename = "FILENAME.txt";
    
       public static void main(String[] args) {
    
          Scanner scan = null;
          File f = new File(filename);
          try {
             scan = new Scanner(f);
          } catch (FileNotFoundException e) {
             System.out.println("File not found.");
             System.exit(0);
          }
    
          int total = 0;
          boolean foundInts = false; //flag to see if there are any integers
    
          while (scan.hasNextLine()) { //Note change
             String currentLine = scan.nextLine();
             //split into words
             String words[] = currentLine.split(" ");
    
             //For each word in the line
             for(String str : words) {
                try {
                   int num = Integer.parseInt(str);
                   total += num;
                   foundInts = true;
                   System.out.println("Found: " + num);
                }catch(NumberFormatException nfe) { }; //word is not an integer, do nothing
             }
          } //end while 
    
          if(!foundInts)
             System.out.println("No numbers found.");
          else
             System.out.println("Total: " + total);
    
          // close the scanner
          scan.close();
       }
    

提交回复
热议问题