简体   繁体   English

读取文件并在Java中打印最大和最小编号

[英]reading file and print max and min number in java

I need to print the maximum and the minimum number inside this file... i tried everything and i cant seem to make it work. 我需要在此文件中打印最大和最小数量...我尝试了所有操作,但似乎无法正常工作。 I am a beginner please help 我是初学者,请帮忙

public class Banck {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        System.out.println("Welcome to JEEEZBANK");

        final int NUM_TO_QUIT = -99;

        String userin ;
        int num;

        System.out.println("Enter a file ending with .txt");
        Scanner scan = new Scanner(System.in);
        userin = scan.nextLine();

        // create file
        PrintWriter file = new PrintWriter(userin);

        for(int i=1; i<5; i++){
            System.out.println("enter first number "+i +" or -99 to quit");
            num = scan.nextInt();
            if(num == NUM_TO_QUIT){
                System.out.println("bye");
                System.exit(0);
            }
            file.println(num);

        }
        file.close();
        // read file and print smallest and biggest number
        Scanner read = new Scanner(file);
        while(read.hasNext()){

            // add the numbers to the array 
            int[] numlist = {num};
            // print the biggest and smallest number inside the numlist array.
        }
    }
}

One way is to create two variables where one keeps track of the current lowest number and the other keeps track of the current highest. 一种方法是创建两个变量,其中一个跟踪当前最低的数字,另一个跟踪当前最高的数字。 For every number in the file, compare if it is lower then the current lowest number, if so replace it or if it is higher then the current highest number (and if so replace it). 对于文件中的每个数字,请比较它是否小于当前最低数字,如果是则替换它,或者如果它大于当前最高数字(如果是替换它)。

You could actually compare and look for the min and max numbers while the user is inputting them instead of having a separate loop, since I presume that they are the same numbers. 实际上,您可以在用户输入它们时比较并查找最小和最大数字,而不用进行单独的循环,因为我认为它们是相同的数字。

Don't keep a list. 不要保留清单。 Use two variables to keep track of max & min. 使用两个变量来跟踪最大值和最小值。

int min = Integer.MAX_VALUE;

int max = 0;

if(num < min) min = num;

if(num > max) max = num;

Assuming num is the integer being read from the file in the loop above. 假设num是上面循环中从文件中读取的整数。

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

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