栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/515427.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号