簡體   English   中英

讀取文件並在Java中打印最大和最小編號

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

我需要在此文件中打印最大和最小數量...我嘗試了所有操作,但似乎無法正常工作。 我是初學者,請幫忙

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.
        }
    }
}

一種方法是創建兩個變量,其中一個跟蹤當前最低的數字,另一個跟蹤當前最高的數字。 對於文件中的每個數字,請比較它是否小於當前最低數字,如果是則替換它,或者如果它大於當前最高數字(如果是替換它)。

實際上,您可以在用戶輸入它們時比較並查找最小和最大數字,而不用進行單獨的循環,因為我認為它們是相同的數字。

不要保留清單。 使用兩個變量來跟蹤最大值和最小值。

int min = Integer.MAX_VALUE;

int max = 0;

if(num < min) min = num;

if(num > max) max = num;

假設num是上面循環中從文件中讀取的整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM