从txt文件中仅读取整数并将每个发现的值相加

从txt文件中仅读取整数并将每个发现的值相加,第1张

从txt文件中仅读取整数并将每个发现的值相加

编辑:
您必须原谅我,该方法将不起作用。您需要做的是一次读取一行,然后按每个空格将其分开,以获得一组单词。从那里您可以识别整数并存储值。

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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5506488.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存