您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

从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();
   }
其他 2022/1/1 18:28:10 有459人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶