如何在Java文本文件中找到最大和最小的数字?

时间:2020-03-05 00:54:28

标签: java

我的教授要求我编写一个程序,该程序可以分析文本文件并打印出该文件的最小值和最大值。我编写了以下代码:

import java.util.Scanner;
import java.io.File;
public class findMaxAndMin {
    public static void main(String[] args) {
        File myFile = new File("NumberFile.txt");
        try {
            Scanner doubleScanner = new Scanner(myFile);
            while (doubleScanner.hasNextDouble()) {
                double currentDouble = doubleScanner.nextDouble();
                System.out.println(currentDouble);
                double biggestNumber = doubleScanner.nextDouble();
                double smallestNumber = doubleScanner.nextDouble();
                if (currentDouble > biggestNumber) {
                    currentDouble = biggestNumber;
                }
                if (currentDouble < smallestNumber) {
                    currentDouble = smallestNumber;
                }
                System.out.println("The largest number is " + biggestNumber);
                System.out.println("the smallest number is " + smallestNumber);
            }
        } catch (Exception l) {
            System.err.println(l.getMessage());
        }
    }
}

我最终在Git命令行中得到了这个明显不正确的混乱输出:

$ java findMaxAndMin
100.0

The largest number is 200.0

the smallest number is 20.0

2.0

The largest number is 550.0

the smallest number is 7000.0

文本文件具有以下值:

100

200

20

2

550

7000

因此,该程序应打印出两个语句,声明“最小数字为2”和“最大数字为7000”。如何轻松纠正此代码?我不是一个经验丰富的程序员。及时答复将不胜感激,因为此作业应在午夜进行。

2 个答案:

答案 0 :(得分:2)

我建议大声朗读代码。这是一种基本的调试方法,称为Rubber Duck Debugging

大学是关于学习的。如果我发现了问题并将其展示给您,实际上会损害您的学习。 (好的成绩很棒,但是赚得更好!)

答案 1 :(得分:1)

如果我是你,我会这样。

import java.util.Scanner;
import java.io.File;
public class Test {
    public static void main(String[] args) {
        File myFile = new File("NumberFile.txt");
        try {
            Scanner doubleScanner = new Scanner(myFile);
            double bigDouble = Double.MIN_VALUE; //Initialize with a very small value
            double smallDouble = Double.MAX_VALUE; //Initialize with a very big value
            double currentDouble;
            while (doubleScanner.hasNextDouble()) {
                currentDouble = doubleScanner.nextDouble();
                if (currentDouble > bigDouble) {
                    bigDouble = currentDouble; //find the biggest number in file
                }
                if (currentDouble < smallDouble) {
                    smallDouble = currentDouble; //find the smallest number in the file
                }
            }
            System.out.println("The largest number is " + bigDouble); //print the number outside the while loop
            System.out.println("the smallest number is " + smallDouble);
        } catch (Exception l) {
            System.err.println(l.getMessage());
        }
    }
}

输出将显示:

Output from the input file

由于您是编程新手,所以我添加了一些注释以帮助您。我建议您摆弄一些代码,以了解更改如何影响输出。

相关问题