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

时间:2018-02-12 01:41:08

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

任何帮助将不胜感激!

5 个答案:

答案 0 :(得分:1)

这里是固定代码。而不是使用

拆分输入
" "

你应该使用

拆分它
","

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

答案 1 :(得分:1)

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

详细说明:

  • ^在行的开头断言位置
  • (?<>)命名为Capture Group
  • [^]匹配列表中不存在的单个字符
  • +匹配一次且无限次

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 :(得分:1)

如果你的线条数量很少,符合你指定的格式,你可以试试这个(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);

答案 3 :(得分:1)

您的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 :(得分:0)

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

     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