JAVA从文本文件中找出最大的差异对

时间:2015-10-16 19:06:11

标签: java

需要帮助解决这个问题,如何逐行读取此文件,按对计算每个差异并输出最大差异对?

输入文本文件格式:

157 901
715 322
51 421
85 128
167 292
6 45
89 1787
84 217
560 128
37 1320

1 个答案:

答案 0 :(得分:2)

所以这是帮助你的东西

import java.util.Scanner;

public class Compute
{

public static void main(String[] args)
{
    Scanner scan = new Scanner("C:/path to file");
    int biggest = 0, num1 = 0, num2 = 0, current1, current2;
    while(scan.hasNextInt())
    {
        current1 = scan.nextInt();
        current2 = scan.nextInt();
        if((Math.abs(current1-current2)) > biggest)   //current1 - current2?  or current2 - current1?  You decide
        {
            biggest = Math.abs(current1-current2);  //if you change that also change this
            num1 = current1;
            num2 = current2;
        }
    }

    System.out.println("The pair with the biggest difference is: "+num1+" and "+num2+". Their difference is: "+biggest);
    scan.close();
}

}