繁体   English   中英

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

[英]JAVA- Read integers from txt file and compute integers

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

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

正则表达式^(?<name>[^,]+),(?<score>[^%]+)

细节:

  • ^在行首处声明位置
  • (?<>)命名为捕获组
  • [^]匹配列表中不存在的单个字符
  • +无限次匹配

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%

如果只有少数几行符合您指定的格式,则可以尝试以下(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);

您的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);
}

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

     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%

说明:

我正在使用以下正则表达式(?<=,)\\\\d+(?=%) n从每行中提取,%字符之间的数字。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM