代码之家  ›  专栏  ›  技术社区  ›  Hunter Landers

有人能很好地理解外部文件吗?

  •  0
  • Hunter Landers  · 技术社区  · 11 年前

    我应该创建一个程序,读取一个每行有3个整数的外部文件,并用这三个数字找到三角形的面积。我们还没有学习数组,所以我想创建一个没有数组的程序,方法和类都可以。我只需要帮助逐行阅读文件中的每三个数字。

    数据为:

    7 8 9

    9 9 12

    6 5 21

    24 7 25

    13 12 5

    50 40 30

    10 10 10

    82 34 48

    4 5 6

    以下是我目前的情况:

    import java.io.*;
    import java.util.*;
    import java.lang.*;
    public class Prog610a
    {
        public static void main(String[] args) throws IOException
        { 
            BufferedReader reader = new BufferedReader(new FileReader("myData.in"));
            String currentLine;
    
            int a, b, c; 
            double s, area;
    
            System.out.println("A" + "\t B" + "\t C" + "\t Area");
            try
            {
                while((currentLine = reader.readLine()) != null)
                {
                    Scanner scanner = new Scanner(currentLine);
    
                    s = ((scanner.nextInt() + scanner.nextInt() + scanner.nextInt()) / 2);
                    area = Math.sqrt(s * (s - scanner.nextInt()) * (s - scanner.nextInt()) * (s - scanner.nextInt()) );
    
                    if(s < 0)
                    {
                        System.out.println(scanner.nextInt() + " \t" + scanner.nextInt() + 
                        " \t" + scanner.nextInt() + "\t This is not a triangle");
                    }
                    else
                    {
                        System.out.println(scanner.nextInt() + " \t" + scanner.nextInt() + 
                        " \t" + scanner.nextInt() + " \t" + area);
                    }
                }
            } 
            finally 
            {
                reader.close();
            }
        }
    }
    
    1 回复  |  直到 11 年前
        1
  •  1
  •   Matthew Franglen    11 年前

    使用 Scanner 。我建议仅使用它可能是不够的,因为您最终可能会出现一些错误的行。为了处理它们,您可能希望将处理分为两部分:获取一行,然后从该行获取各个值。

    这允许您捕捉值不足或值过多的行。如果不这样做,则可能会与行不对齐,从一行读取一些值,从下一行读取某些值。

    这个 BufferedReader 将允许您读取可以扫描的行。由于不想使用数组,因此必须单独提取数字:

    BufferedReader reader = new BufferedReader(new FileReader("myData.in"));
    String currentLine;
    
    try {
        while ((currentLine = reader.readLine()) != null) {
            Scanner scanner = new Scanner(currentLine);
    
            try {
                calculateTriangleArea(
                    scanner.nextInt(), scanner.nextInt(), scanner.nextInt()
                );
            }
            catch (NoSuchElementException e) {
                // invalid line
            }
        }
    }
    finally {
        reader.close();
    }
    

    它还可以帮助您理解Java字符串插值。你有 horizontalTab 在整个代码中。只需使用 \t 。例如:

    "\tThis is indented by one tab"
    "This is not"
    

    您可以找到字符串转义字符的完整列表 here .

    我的代码中的异常处理(或缺少)可能会让您感到惊讶。在您的代码中 Exception 可能会被抛出。但是,您放弃它,然后继续在已知已损坏的扫描仪上执行其余代码。在这种情况下,最好立即失败,而不是隐瞒错误并试图继续。

    在我的代码中确实发生的一点异常处理是 finally 块这确保了无论在读取读取器时发生什么情况,读取器都是关闭的。它包装了读取器打开后执行的代码,因此,已知读取器不为空,使用后应关闭。