JAVA-从txt文件中读取整数并计算整数

标签 java arrays regex parsing bufferedreader

我需要一些有关以下代码的帮助。 我想做的是编写一个程序来读取文件并计算平均成绩并将其打印出来。我尝试了多种方法,例如将文本文件解析为并行数组,但遇到了成绩末尾有 % 字符的问题。下面的程序也旨在将整数相加,但输出是“未找到数字”。

这是文本文件的剪辑(整个文件有 14 行类似的输入):

Arthur Albert,74% 
Melissa Hay,72%
William Jones,85%
Rachel Lee,68%
Joshua Planner,75%
Jennifer Ranger,76%

这是我到目前为止所拥有的:

final static String filename = "filesrc.txt";

public static void main(String[] args) throws IOException {

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

任何帮助将不胜感激!

最佳答案

这是固定代码。而不是使用分割输入

" "

你应该使用

来分割它
","

这样,当您解析分割字符串时,您可以使用 substring 方法并解析输入的数字部分。

例如,给定字符串

Arthur Albert,74%

我的代码会将其分为 Arthur ALbert74%。 然后我可以使用 substring 方法并解析 74% 的前两个字符,这将给我 74。

我编写代码的方式使其可以处理 0 到 999 之间的任何数字,并在我添加了您尚未添加的内容时添加了注释。但是,如果您仍有任何疑问,请不要害怕提问。

final static String filename = "filesrc.txt";

public static void main(String[] args) throws IOException {

          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
             int successful = 0; // I did this to keep track of the number of times
             //a grade is found so I can divide the sum by the number to get the average

          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) {
                 System.out.println(str);
                try {
                    int num = 0;
                    //Checks if a grade is between 0 and 9, inclusive
                    if(str.charAt(1) == '%') {
                        num = Integer.parseInt(str.substring(0,1));
                        successful++;
                        total += num;
                       foundInts = true;
                       System.out.println("Found: " + num);
                    }
                    //Checks if a grade is between 10 and 99, inclusive
                    else if(str.charAt(2) == '%') {
                        num = Integer.parseInt(str.substring(0,2));
                        successful++;
                        total += num;
                       foundInts = true;
                       System.out.println("Found: " + num);
                    }
                    //Checks if a grade is 100 or above, inclusive(obviously not above 999)
                    else if(str.charAt(3) == '%') {
                        num = Integer.parseInt(str.substring(0,3));
                        successful++;
                        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/successful);

          // close the scanner
          scan.close();
       }

关于JAVA-从txt文件中读取整数并计算整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48738461/

相关文章:

java - 如何查找结果集的磁盘使用情况?

java - .NET 中的 POST 多部分/混合

java - JTextArea append() 方法写入两次?

java - Array Try Catch 无法识别 if 语句中的数组长度

Java : How to remove all characters in String except a a-z, 数字和德语字符

Python - 用句点替换括号并删除第一个和最后一个句点

java - JTable 如何在插入删除或更新数据后刷新表模型。

整数数组初始化的 C++ 指针

javascript - 将序列化数据转换为数组或对象

regex - 从正则表达式中排除一些单词