有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我需要一些关于下面代码的帮助。 我要做的是编写一个程序,读入文件,计算平均分数,然后打印出来。我尝试过几种方法,比如将文本文件解析为并行数组,但我遇到了将%字符放在成绩末尾的问题。下面的程序也用于将整数相加,但输出为“找不到数字”

这是文本文件的剪辑(整个文件有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();
       }            
}

任何帮助都将不胜感激


共 (5) 个答案

  1. # 1 楼答案

    正则表达式^{}

    详情:

    • ^断言行开始处的位置
    • (?<>)命名的捕获组
    • [^]匹配列表中不存在的单个字符
    • +一次和无限次之间的匹配

    Java代码

    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    
    final static String filename = "C:\\text.txt";
    
    public static void main(String[] args)  throws IOException 
    {
        String text = new Scanner(new File(filename)).useDelimiter("\\A").next();
        final Matcher matches = Pattern.compile("^(?<name>[^,]+),(?<score>[^%]+)").matcher(text);
    
        int sum = 0;
        int count = 0;
        while (matches.find()) {
            sum += Integer.parseInt(matches.group("score"));
            count++;
        }
    
        System.out.println(String.format("Average: %s%%", sum / count));
    }
    

    输出:

    Avarege: 74%
    
  2. # 2 楼答案

    您可以通过以下方式更改代码:

         Matcher m;
         int total = 0;
         final String PATTERN = "(?<=,)\\d+(?=%)";
         int count=0;
         while (scan.hasNextLine()) { //Note change
            String currentLine = scan.nextLine();
            //split into words
            m =  Pattern.compile(PATTERN).matcher(currentLine);
            while(m.find())
            {
                int num = Integer.parseInt(m.group());
                total += num;
                count++;
            }
         } 
    
         System.out.println("Total: " + total);
         if(count>0)
             System.out.println("Average: " + total/count + "%");
    

    对于您的输入,输出是

    Total: 450
    Average: 75%
    

    解释:

    我使用下面的regex(?<=,)\\d+(?=%)n从每一行中提取,%字符之间的数字

    正则表达式用法:https://regex101.com/r/t4yLzG/1

  3. # 3 楼答案

    您的split方法是错误的,并且您没有使用任何PatternMatcher来获取int值。下面是一个工作示例:

    private final static String filename = "marks.txt";
    
    public static void main(String[] args) {
        // Init an int to store the values.
        int total = 0;
    
        // try-for method!
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(filename))) {
            // Read line by line until there is no line to read.
            String line = null;
            while ((line = reader.readLine()) != null) {
                // Get the numbers only uisng regex
                int getNumber = Integer.parseInt(
                        line.replaceAll("[^0-9]", "").trim());
                // Add up the total.
                total += getNumber;
            }
        } catch (IOException e) {
            System.out.println("File not found.");
            e.printStackTrace();
        }
        // Print the total only, you know how to do the avg.
        System.out.println(total);
    }
    
  4. # 4 楼答案

    如果您有少量符合指定格式的行,您可以尝试此(IMO)功能性解决方案:

    double avg = Files.readAllLines(new File(filename).toPath())
                .stream()
                .map(s -> s.trim().split(",")[1]) // get the percentage
                .map(s -> s.substring(0, s.length() - 1)) // strip off the '%' char at the end
                .mapToInt(Integer::valueOf)
                .average()
                .orElseThrow(() -> new RuntimeException("Empty integer stream!"));
    
    System.out.format("Average is %.2f", avg);
    
  5. # 5 楼答案

    这是固定密码。而不是使用

    " "
    

    你应该使用

    ","
    

    这样,在解析拆分字符串时,可以使用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();
           }