如何通过从文件中读取整数来查找整数的次数和最长的序列?

时间:2017-10-02 22:58:29

标签: java

我必须让用户输入一个整数,然后通过读取一个文件,我必须找到整数出现的次数,然后是最长的数字序列。我想我通常有找到这两件事的方法,但我不认为我正在从文件中读得非常正确。我正在使用eclipse,所以我的文件必须在某个地方才能被阅读,或者我的代码是完全错误的?

import java.util.Scanner;
import java.io.File;


    int[]data;
    int []counter;
    int temp;



        random.data = new int[5000];
        try{
            random.readDataFromFile();
        }
        catch(Exception e){

        }
        random.findInteger();

        random.longSequence();
    }
    //method to receive the input from the user and prints the number of times that the value occurs 

    public void readDataFromFile() throws Exception {
        java.io.File infile = new java.io.File("5000RandomNumbers.txt");
        Scanner input = new Scanner(infile);
        for (int i = 0; i < data.length; i++) {
            data[i] = input.nextInt();
            }
        input.close();
    }


    public void findInteger(){

        Scanner input = new Scanner (System.in);



        //ask user for an integer
        System.out.println("Please enter an integer value");

        for (int i = 0; i < data.length; i++){
            data[i] = input.nextInt();
        }

        input.close();

        for (int i = 0; i < data.length; i++){
            temp = data[i];
            counter[temp]++;
        }

        for (int i = 0; i <counter.length; i++){
            if (counter[i] > 0 && counter[i]==1){
                System.out.println(i + "occurs" + counter[i] + "times");
            }

            else if (counter[i]>= 2){
                System.out.println(i + "occurs" + counter[i] + "times");
            }
        }
    }

    //method that prints out the longest increasing sequence in the data
    public void longSequence(){
        int count = 1;
        int max = 1;

        for (int i = 1; i < data.length; i++){
            if (data[i] >= data[i-1]){
                count ++;
            }

            else{
                count = 1;

            }

            if (count > max){
                max = count;
            }
        }
        System.out.println(max);
    }

}

1 个答案:

答案 0 :(得分:0)

您可以尝试使用HashMap

HashMap hmap = new HashMap();

hmap.put(key, value);

您可以将密钥作为要检查的int,将值作为计数器。